0

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 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

2 Comments

So when you explicitly call the base class constructor with the argument in the derived's member initialization list, is it not initializing the same data member another time? as the A's constructor would have already been called before reaching this space. Does it not look like initializing twice?
@IbrahimQuraish No. You say "A's constructor would have already been called before reaching this space" but that's false. If you explicitly call it, then A's constructor will run with the parameters that you provide and then the rest of the init list is done.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.