質問

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 !

役に立ちましたか?

解決

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.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top