public:
const int x;
base():x(5){}
};
class der : public base {
public:
der():x(10){}
};
der d;
My aim is when instance of base class is created it will initialise x as 5 and when instance of der class is created it will initialise x as 10. But compiler is giving error.
As x is inherited from class base, why is it giving error?
You can’t initialize a base class member in the initializer list for a constructor in the derived class. The initializer list can contain bases, and members in this class, but not members in bases.
Admittedly, the standardese for this isn’t entirely clear. 12.6.2/2 of C++03:
It means “(a nonstatic data member of the constructor’s class) or (a direct or virtual base)”. It doesn’t mean “a nonstatic data member of (the constructor’s class or a direct or virtual base)”. The sentence is ambiguous, but if you took the second reading then you couldn’t put bases in the initializer-list at all, and the very next sentence in the standard makes it clear that you can.
As for why it’s not allowed, that’s a standard rationale question and I’m guessing at the motives of the authors of the standard. But basically because it’s the base class’s responsibility to initialize its own members, not the derived class’s responsibility.
Probably you should add an
intconstructor tobase.