C ++ - constructor where parameters are used by base class' Constructor
I have a Car class that inherits from Vehicle class. The Vehicle and Vehicle class uses the wheel parameter. From my understanding of how inheritance works, the Car object will be built in two steps: Vehicle will build first by calling its Constructor and then Car, which will also call it constructor. My question is, how do I write my Car constructor when its parameters are used by the Vehicle constructor?
class Vehicle {
public:
Vehicle(int wheels);
};
class Car {
public:
Car(int wheels): Vehicle(wheels);
};
source to share
You pass the wheels to the vehicle's constructor, then process additional parameters in the Car's constructor.
class Car : public Vehicle {
public:
Car(int otherParam, int wheels);
};
Car::Car(int otherParam, int wheels) : Vehicle(wheels) {
//do something with other params here
}
Of course, you can have several other parameters, and they don't have to be integers;)
EDIT: I also forgot to inherit from vehicle in my original example, thanks to perreal for pointing this out.
source to share
Ok first,
class Car:public Vehicle{...
I'm not sure what you mean by "how can I write myCars constructor"
Vehicle(int wheels):m_Wheels(wheels)
{
// or m_Wheels = wheels;
}
...
Car(int wheels):Vehicle(wheels)
{
if(m_Wheels != 4)
fprintf(stdout, "Uh Oh");
}
In this case, the vehicle's constructor is called and then the vehicle's constructor is called. Please note that I can use m_Wheels in Car since it was initialized in Vehicle.
Does this answer your question?
source to share