Domanda

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?

È stato utile?

Soluzione

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.

Altri suggerimenti

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).

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top