Constructors and inheritance?

Let's say that I have a Car class and another that inherits from Car called SuperCar. How can I guarantee that the Car costructor is called in the SuperCar constructor? I just do: Car.Car (// args) ;?

thanks

+4
source share
6 answers

In the SuperCar constructor, add : Car(... your arguments ...) between the constructor header and the constructor body.

Code example:

 #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 the SuperCar subclass of Car confusing, you should probably avoid this.

+3
source

Examples of classes without membership 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*/} }; 
+5
source

Example:

 SuperCar::SuperCar(Parameter p) : Car(p){ //some voodoo... } 

If I remember it right

edit: damn, kriss was faster :)

+3
source

In the constructor of the derived class, define the initializer of the base class with the required parameters:

 SuperCar(/*params*/) : Car(/*differentParams*/) { } 
+1
source

The SuperCar constructor will look like this:

 SuperCar(int sayForExample):car(sayForExample),m_SuperCarMember(sayForExample) { // constructor definition } 

This will invoke the specific car(int) constructor and initialize the SuperCar element m_SuperCarMember ..

Hope this helps.

+1
source

You can do this using a list of initializers.

 SuperCard::SuperCar(args):Car(args){ //Supercar part} 
0
source

All Articles