Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ - Constructor Where Parameters Are Used By Base Class' Constructor

I have a Car class that inherits a Vehicle class. Both the Car and Vehicle class takes in the parameter, 'wheels'. From my understanding of how inheritance works, the object Car would be constructed in two phases: Vehicle would construct first by calling its Constructor, followed by Car which would also call its constructor. My question is how would I write my Car's constructor when its parameters are being used by the Vehicle's constructor?

class Vehicle {
public:
    Vehicle(int wheels);
};

class Car {
public:
    Car(int wheels): Vehicle(wheels);
};
like image 954
user27279 Avatar asked Mar 13 '12 21:03

user27279


1 Answers

You need to inherit from Vehicle:

Header file:

class Car: public Vehicle {
public:
    Car(int wheels);
};

Cpp file:

Car::Car(int wheels): Vehicle(wheels) {
}
like image 138
perreal Avatar answered Oct 11 '22 23:10

perreal