2

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?

Community
  • 1
  • 1
Aniol
  • 125
  • 7
  • `B() : A(3), CONSTANT_B(3) {}` will ensure the members are initialised as intended. There is no way to make `CONSTANT_B` be initialised before `A`s constructor though. – Peter Dec 29 '16 at 14:42

1 Answers1

5

Your constant B::CONSTANT_B can be static, since it does not depend on a constructor argument.

statics are initialised before your class objects are constructed (unless those are static too!).

struct B : A
{
    static const int CONSTANT_B = 3;

    B() : A(CONSTANT_B)
    {
        write();
    }
};

If B::CONSTANT_B itself took its value from a constructor argument, you'd probably have to name that argument twice in the ctor-member-initialiser. There are no trivial workarounds for that as far as I can imagine.

struct B : A
{
    const int CONSTANT_B;

    B(const int constant)
       : A(constant)
       , CONSTANT_B(constant)
    {
        write();
    }
};
Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055