user27279
user27279

Reputation: 155

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);
};

Upvotes: 9

Views: 37754

Answers (5)

perreal
perreal

Reputation: 98108

You need to inherit from Vehicle:

Header file:

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

Cpp file:

Car::Car(int wheels): Vehicle(wheels) {
}

Upvotes: 22

Michael Wilson
Michael Wilson

Reputation: 442

What you're looking for is:

Car::Car(int wheels)
:Vehicle(wheels) 
{
 // Do Car constructor specific stuff here.
}

The :Vehicle(wheels) will pass the wheels parameter up the line to the Vehicle constructor, and it will construct in the order you describe.

Upvotes: 0

Kerrek SB
Kerrek SB

Reputation: 477504

Either inline:

Car(int wheels) : Vehicle(wheels) { }

Or out-of-line:

class Car : public Vehicle {
  Car(int); 
  // ...  
};

Car::Car(int wheels) : Vehicle(wheels) { }

Upvotes: 0

Adam Reed
Adam Reed

Reputation: 3314

Well firstly,

      class Car:public Vehicle{...

I am not sure what you mean by "how would 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 constructor is called and then the car constructor is called. Note that I can use m_Wheels in Car, as it was initialized in Vehicle.

Does this answer your question?

Upvotes: 0

Moritz
Moritz

Reputation: 4771

You pass wheels to the Vehicle constructor, then handle the additional params in the Car 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 multiple other params and they don't need to be integers ;)

EDIT: I also forgot to inherit from vehicle in my initial example, thanks perreal for pointing that out.

Upvotes: 7

Related Questions