Re: Passing *this in constructor
On Jun 5, 6:57 pm, Victor Bazarov <v.Abaza...@comAcast.net> wrote:
tech wrote:
However some of my subobjects need to have a reference to
their owner object.
Can i do the following then ie pass *this in the constructor
of A, i was concerned maybe the A object is not fully
constructed. If this is not way to do how to do?
/.h file
class A
{
public:
A();
~A();
private:
obj1 myobj1;
};
/.cpp file
A::A()
: myobj1(*this) <- CHANGE MADE HERE
{
}
A::~A()
{
}
Obviously constructor of obj1 takes reference to A
class obj1
{
private:
obj1& m_obj;
I think you meant
A& m_obj;
};
obj1(A& a):m_obj(a)
{
}
The answer is "Yes, you can". Be careful, though, not to call
any member functions or access any data members of 'a' in the
'obj1' constructor because 'a' hasn't been fully constructed
yet.
The answer is "yes, you can" in this simple case. If the object
expects a reference to a base class, however, you have undefined
behavior (and I've encountered cases where it doesn't work),
since conversion to base is also undefined behavior. Why this
is so, I don't know, since the compiler must be able to do the
conversion in order to call the constructor of the base classes,
or to call functions in the base classes from within the
constructor, but I've had it actuallly fail (admittedly only in
cases of virtual inheritance).
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34