amrhassan amrhassan - 1 month ago 17
C++ Question

How can I initialize base class member variables in derived class constructor?

Why can't I do this?

class A
{
public:
int a, b;
}

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

}

Answer Source

You can't initialize a and b in B because they are not members of B. They are members of A, therefore only A can initialize them. You can make them public, then do assignment in B, but that is not a recommended option since it would destroy encapsulation. Instead, create a constructor in A to allow B (or any subclass of A) to initialize them:

class A 
{
protected:
    A(int a, int b) : a(a), b(b) {} // Accessible to derived classes
    // Change "protected" to "public" to allow others to instantiate A.
private:
    int a, b; // Keep these variables private in A
};

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