0
votes

I have a trivial question about C++ behavior. When I try to initialize the base class's data member using derived class's constructor initialization list, I am getting an error. But if I initialize inside the derived class constructor or if I call the base class constructor with the argument in the derived class member initialization list then there is no error. So the question is why I am getting error in the 3rd case.

class A {
protected:
   int data;
public:
   A(int i = 0) : data(i) {}
};
class B : public A {
public:
   B(int i = 0) { data = i; } /* works fine, initializing inside c'tor definition */
   B(int i = 0) : A(i) {} /* calling super class constructor with arg works fine */
   B(int i = 0) : data(i) {} /* error: class B does not have any field named data */
};
int main() {
    B obj1(7);
    B* obj2 = new B(8);    
    A* obj3 = new B(9);
    delete obj2; 
    delete obj3;
}
2

2 Answers

4
votes

This is so because you cannot initialise base class member in a derived class. What you call "initialisation inside the constructor" is not initialisation, it is assignment after the member was already initialised by the constructor of the base class.

0
votes

data is already initialized by A's constructor when we get to the init list of B (the part after the base constructor call if that exists). You cannot initialize something twice. You can either tell A's constructor how to initialize it, or assign something else to the already initialized member.