Home >Backend Development >C++ >How to Properly Initialize Base Class Member Variables in a Derived Class Constructor?

How to Properly Initialize Base Class Member Variables in a Derived Class Constructor?

Barbara Streisand
Barbara StreisandOriginal
2024-12-10 21:54:12261browse

How to Properly Initialize Base Class Member Variables in a Derived Class Constructor?

Initialization of Base Class Member Variables in Derived Class Constructor

When working with class inheritance, a common question arises: how to initialize base class member variables within a derived class constructor. An initial attempt to do so may lead to confusion, as demonstrated below:

class A {
public:
    int a, b;
};

class B : public A {
    B() : A(), a(0), b(0) {
    }
};

This code fails to compile, raising the question: why can't we initialize a and b in B?

The reason lies in the fact that a and b are not members of B. They belong to the base class A. Only A can initialize its own member variables.

One possible solution is to make a and b public members of A, allowing B to assign values directly. However, this is not recommended as it breaks the encapsulation principle.

Instead, a more robust approach is to define a constructor in A that allows derived classes to specify initialization values. This can be achieved by making the constructor protected and accessible to subclasses:

class A {
protected:
    A(int a, int b) : a(a), b(b) {} // Accessible to derived classes
private:
    int a, b; // Keep variables private within A
};

class B : public A {
public:
    B() : A(0, 0) // Calls A's constructor, setting a and b to 0 within A
    {
    }
};

This solution ensures that a and b are initialized correctly within A, guaranteeing data integrity and encapsulation.

The above is the detailed content of How to Properly Initialize Base Class Member Variables in a Derived Class Constructor?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn