Multiple constructors calling parent constructor

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

In the child class:
1
2
3
4
5
6
7
8
9
10
ChildClass::ChildClass()
{
    ChildClass(1);
}

ChildClass::ChildClass(int i)
: ParentClass(i)
{
    // do stuff
}


In the parent class:
1
2
3
4
ParentClass::ParentClass(int i)
{
    // do stuff
}


In my main program:
1
2
3
4
5
6
7
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?
1
2
3
4
ChildClass::ChildClass()
{
    ChildClass(1);
}


This does not do what you think it does.

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.
What if I want 3 constructor options: one with 0 parameters, one with 1 parameter, and another with 2 parameters? How could I make this happen?
If your compiler supports it you can delegate constructors http://ideone.com/GD7Vu8
Topic archived. No new replies allowed.