I need one clarification in c++ linux.
I have class C1 and another class C2. C1 will have the reference of C2.
class C1
{
C2 &obj ;
}
i am thinking of two choices here ,
- Directly holding the reference of
C2asC2 &obj; - Creating the pointer of
C2, asc2* obj;
Which is good ? what is the difference in it ? when choose either?
Avoid using a reference member as much as possible.
The same differences as that of references and pointers apply here,
If you have a reference member then it must be initialized at the time of creation of your class object you cannot have a lazy initialization as in case of pointer member because references cannot be NULL and cannot be reseated, while a pointer member can be made to point to a
C2instance lazily as and when required.Also, note that there are other side effects as well, Once you have a reference member the compiler will not generate the copy assignment operator(
=) & You will have to provide one yourself, It is cubersome to determine what action your=operator shall take in such a case.For most practical purposes(unless you are really concerned of high memory usage due to C2 size) just holding an instance of
C2as member ofC1should suffice, instead of pointer or reference member, that saves you a whole lot of worrying about other problems which reference/pointer members bring along though at expense of extra memory usage.If you must, use a pointer make sure you use a smart pointer instead of a raw pointer, that would make your life much easier with pointers.