This is something that I have encountered for the first time and have spent some time trying to figure out how this would work. So, the problem goes like this. I'd like to have object of one class as private member of another class. I do not want any inheritance between these two classes and can't want to define them as friend.
To show an example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
class class1
{
private:
public:
class1();
};
class class2
{
private:
class1 objA;
public:
class2()
{
//here objA will be used
};
}
Obviously I tried the above and it didn't work. I do not know how to tackle this. It will be great if someone could point out how this is achievable? Also, some clarification of how/when the constructors will be called would be greatly appreciated.
This does work if the classes are declared as you just posted it. The constructors of the member objects are called before the body of the owning classes constructor. If the member objects constructor requires parameters, you can have to use an initialization list: