How to instantiate objects from within another class constructor?

Hi,

I'm trying to instantiate an object from the constructor of another object, but keep getting this error:

error: no matching function for call to 'testChildClass::testChildClass()

I'm giving the constructor the proper prarameter (int) but it seems to not be reading it and thinks its getting empty parameters. I can instantiate the object fine in the main method but cannot in the constructor of another class.

Here is my code:

class testParentClass
{
private:
int newTestVar;

public:
int testVar;
testParentClass(int newTestVar)
{
testVar = newTestVar;
}

void printTestVar()
{
cout << testVar << endl;
}
};

class testChildClass : public testParentClass
{

public:
testChildClass (int newTestVar) : testParentClass (newTestVar){} //constructor

};

Now, if I instantiate testChildClass in main like:

testChildClass childObject = testChildClass(5);

it works but if I make another class:

class testMainClass
{
public:
testChildClass childObject;
testMainClass()
{
childObject = new testChildClass(5);
childObject.printTestVar();
}
};

I get the error. What am I doing wrong?


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.
Last edited on
childObject is not a pointer?

CMIIW
What if I need to instantiate multiple objects in the constructor?
edit: Never mind I think I got it, I can have multiple instantiation in the "initializer list"
Last edited on
Topic archived. No new replies allowed.