Reputation: 54113
Lets say I have a class named Car and another which inherits from Car called SuperCar. How can I ensure that Car's costructor is called in SuperCar's constructor? Do I simply do: Car.Car(//args);?
Thanks
Upvotes: 4
Views: 310
Reputation: 24177
In SuperCar constructor add : Car(... your arguments ...)
between constructor header and constructor body.
Exemple with code:
#include <iostream>
using namespace std;
class Car {
public:
Car() { }
// Oh, there is several constructors...
Car(int weight){
cout << "Car weight is " << weight << endl;
}
};
class SuperCar: public Car {
public:
// we call the right constructor for Car, detected by call arguments
// relying on usual function overloading mechanism
SuperCar(int weight, int height) : Car(weight) {
cout << "SuperCar height " << height << endl;
}
};
int main(){
SuperCar(1, 10);
}
PS: By the way calling SuperCar
a subclass of Car
is confusing, you should probably avoid that.
Upvotes: 3
Reputation: 11648
Your SuperCar
constructor will be like,
SuperCar(int sayForExample):car(sayForExample),m_SuperCarMember(sayForExample)
{
// constructor definition
}
This will invoke the specific constructor car(int)
and initialize the SuperCar
's member m_SuperCarMember
..
Hope it helps..
Upvotes: 1
Reputation: 35450
You can do this using initialiser list.
SuperCard::SuperCar(args):Car(args){ //Supercar part}
Upvotes: 0
Reputation: 54148
On your derived class constructor, define an initializer for the base class with the required parameters:
SuperCar(/*params*/) : Car(/*differentParams*/)
{
}
Upvotes: 1
Reputation: 5766
Sample classes with no member vars.
class Car {
Car(); /*If you want default objects*/
Car(/*arg list*/); /* maybe multiple constructors with different, count and
type args */
};
class SuperCar {
SuperCar(/*args list*/) : Car(/*arg list*/){/*Constructor Body*/}
};
Upvotes: 5
Reputation: 51868
example:
SuperCar::SuperCar(Parameter p) : Car(p){
//some voodoo...
}
if i remember correctly
edit: damn, kriss was faster :)
Upvotes: 3