riverside96
riverside96

Reputation: 19

Explicitly initalize abstract base class constructor with value determined by parameter of derived class constructor

Within my vehicle base class, I have a private member variable, string type (for type of vehicle, ie car, motorbike, tricycle, etc).

#pragma once
using namespace std;

#include <string>
#include <iostream>

class vehicle {
public:
  vehicle(string reg, string make, string model, int age, string type);
  virtual ~vehicle() = default;
  virtual double costPerDay() = 0;
protected:
  int age;
  int perDayCostCap(int costPD);
  double penceToPounds(int pence);
private:
  const string type;
  string const reg, make, model;
};

One of the derived classes, bike, has a numberOfWheels variable which is to be passed into its constructor. I want to initialize the base class constructor with type bicycle or tricycle depending on the numberOfWheels.

I can not figure out how to achieve this, seeing as the base class constructor has to be initialized before the function body of the child class.

The following shows what I would like to achieve (though, I know this is not possible):

bike::bike(int engineCC, int numOfWheels, string reg, string make, string model, int age)
  :engineCC(engineCC), numOfWheels(numOfWheels) {
  string tricOrBic = (numOfWheels == 2) ? "bicicle" : "tricicle";
  vehicle:reg=reg, make=make, model=model, age=age, type=tricOrBic;
};

Upvotes: 0

Views: 39

Answers (1)

john
john

Reputation: 87959

Like this?

bike::bike(int engineCC, int numOfWheels, string reg, string make, string model, int age)
    : vehicle(reg, make, model, age, numOfWheels == 2 ? "bicycle" : "tricycle")
    , engineCC(engineCC)
    , numOfWheels(numOfWheels)
{
}

This is normal programming, maybe you had some problem I'm not seeing.

Upvotes: 2

Related Questions