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

      

+3


source to share


5 answers


You forgot to inherit from Vehicle:

Header file:

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

      



Cpp file:

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

      

+7


source


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.

+3


source


Or built-in:

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

      

Or out of line:

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

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

      

0


source


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?

0


source


What are you looking for:

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

      

:Vehicle(wheels)

will pass the wheel parameter along the line to the vehicle constructor and it will be built in the order you describe.

0


source







All Articles