j b
j b

Reputation: 5306

Is it OK to pass member object in base class initialiser list?

I have two classes where one is a base class containing a pointer to a member object on a derived class.

Like this:

class Bar { };

class Foo : Bar { };

class A
{
    public:
         A(Foo *foo) { this->foo = foo };

    private:
        Foo *foo;
}

class B : public A
{
    public:
        B() : A(&bar) { };

    private:
        Bar bar;
}

My question is: is B.bar guaranteed to be allocated before being passed as an initialisation parameter to the constructor of A?

Put another way: if I create an instance of B is B->foo guaranteed to be a valid pointer to an instance of a Bar?

Upvotes: 2

Views: 621

Answers (2)

kwesolowski
kwesolowski

Reputation: 724

Keep in mind that while the particular example works (object is allocated so taking addresses of its members works), it is not a universally valid pattern (which I just learned hard way).

There is implicit cast B* to A*, which in this case is trivial, in case of having virtual methods and more complex objects can introduce offset (it can be executed on uninitialized memory), and in case of virtual inheritance would cause SegFault - if B inherited A virtually and as implementation detail B contained pointer to A and allocated it dynamically).

Upvotes: 0

Kerrek SB
Kerrek SB

Reputation: 477710

The base subobject is constructed before the member objects. Pointers and references to all the members are valid, but you must not access the actual objects until they are constructed.

Upvotes: 8

Related Questions