I have a class that extends another class, and I want multiple constructors in the child class, but the child constructor needs to call the parent constructor. This is what I have
ChildClass child1;
// do stuff with child1
// breaks
ChildClass child2(1);
// do stuff with child2
// works fine
Using the default constructor breaks my program at runtime, but using the one with a parameter works fine. The default constructor calls the other with the same thing as the main part in the program, so I would think this should make no difference, but obviously that isn't the case.
Why is this happening? What am I doing wrong?
When you call ChildClass(1) here... you are constructing a new temporary object, then immediately throwing it away. You are not calling your other constructor from this one.
The easiest way to do this would be to get rid of the parameterless constructor, and simply give 'i' a default value of 1 in the parametered ctor:
1 2 3 4 5 6
class ChildClass : public ParentClass
{
public:
// ChildClass(); // <- get rid of this
ChildClass(int i = 1); // <- give this a default value of 1
};
Now when you default construct an object, it will actually call the parameter constructor with i=1.