You get that error because the
childObject member in
testMainClass is being constructed with the default constructor (which you haven't provided in
testChildClass).
Also, this:
childObject = new testChildClass(5);
doesn't make sense (in C++) because
childObject is not a pointer to a
testChildClass. Note that with the way you have it,
childObject is being instantiated with the default constructor before the body of the
testMainClass constructor is even executed.
Instantiating
childObject as part of an initializer list like this will make the error go away:
1 2 3 4 5 6 7 8 9 10 11 12
|
class testMainClass
{
public:
testChildClass childObject;
testMainClass()
: childObject(5)
{
childObject = new testChildClass(5); //instantiated above in initializer list
childObject.printTestVar();
}
};
|
Finally, this:
testChildClass childObject = testChildClass(5);
can be rephrased more efficiently as this:
testChildClass childObject(5);
In the former, a temporary object of
testChildClass is constructed, then the copy constructor of
childObject is invoked and then the temporary object is destructed. In the latter, only the constructor of
childObject is invoked.