On Nov 10, 8:03*am, Morya <mda...@gmail.comwrote:
Hi,
I had a scenario where classes had two way composition (Already
present in a huge code. Wasn't introduced by me) something like this:
A {
public:
A ()
: b(*this)
{}
private:
B b;
};
B {
public B (A aobj) : a(aobj) {}
private:
A a;
};
I believe this code is not valid *(undefined behavior ??) as A *is not
fully constructed when it is passed to B. I googled around but didn't
find a direct reference of such situation. Any hints? pointers ?
~Moh
I don't know what is the expected behavior of the above code, if any.
But if you are looking for a solution to your problem, you might
consider changing class B's member a to be of type A& or A*. That way
a would refer/point to the right object. Of course, this solution may
not be practical if B must have its private copy of the A stored in a.
Here's the reference option (similarly you could write the pointer
option):
A {
public:
A ()
: b(*this)
{}
private:
B b;
};
B {
public B (A& aobj) : a(aobj) {}
private:
A& a; // a is now a reference
};