Aniol
Aniol

Reputation: 115

Change the order of constructors in inheritance

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:

Is there a way to force member constants to initialize first?. Which is the cleanest way to do it?

Upvotes: 2

Views: 292

Answers (1)

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385405

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

Upvotes: 5

Related Questions