Question

I have this hierarchy :

struct Params { int k = 17; };
struct A
{
    A(Params& par): _p(par)
    { }

    Params& _p;
};

struct B: public A
{
    using A::A;
    int c{this->_p.k};
};

int main()
{
    Params p;
    B b(p);
    return 0;
}

Can I rest assured that A::_p will always be initialized before calling it in the declaration of B::c ?

Thanks !

Was it helpful?

Solution

Yes, it will be initialized.

The base class has to be fully constructed before the derived class starts to be constructed. So as long as the constructor from A initialized A::_p, the derived classes will always* see it fully initialized.

[*] Of course, with enough effort you can always break things; for example: http://coliru.stacked-crooked.com/a/196a5b0217efbbb1 There I used the comma operator to call B::foo() before anything can be constructed; luckily the compiler detected it as a warning.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top