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;
}