I am struggling with class inheritance construction order. Let's say I have these two classes:
class A {
public:
const int CONSTANT_A;
A(const int constant) : CONSTANT_A(constant) {
}
void write() {
std::cout << CONSTANT_A;
}
};
class B : public A {
public:
const int CONSTANT_B = 3;
B() :A(CONSTANT_B) {
write();
}
};
When a new object B
is created, CONSTANT_A
is not 3 because class inheritance constructors order works as following:
- Construction always starts from the base class. If there are multiple base classes then, it starts from the left most base.
- Then it comes the turn for member fields. They are initialized in the order they are declared.
- At the last the class itself is constructed.
- The order of destructor is exactly reverse.
Is there a way to force member constants to initialize first?. Which is the cleanest way to do it?