Consider this code:
struct A {};
struct B
{
B(A* a) : a(a) {}
private:
A* a;
};
struct base
{
base(B b) : b(b) {}
protected:
A a;
private:
B b;
};
struct derived : public base
{
derived() : base(B(&a)) // <-- IS THIS OK?
{}
};
Here, the base class needs a B object passed to its constructor by the derived class, and the B object refers to an A object, but the A object lives inside the base class.
The constructor of the B object does not do anything to the A pointer except store it, so I’m thinking this should be OK, but it still feels wrong because technically the A object doesn’t yet exist at the time I’m passing it to the base constructor.
Can I get into trouble doing this or should this be OK?
It is safe as long as you don’t use
ainB‘s constructor, as the objectaisn’t constructed yet.I mean, you shouldn’t dereference the pointer
ainB'sconstructor; however afterbase‘s constructor is executed, you can safely dereferenceB::ain other methods ofB.