0

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;
};
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
  • You can use a function to initilize it: `bike::bike():vehicle(reg, make, model, age, tricOrBic(numOfWheels))` with `std::string tricOrBic(int numberOfWheels)`. Not sure if there's any duplicate for that. – Yksisarvinen Nov 15 '22 at 22:34
  • This doesn’t address the question, but unless `penceToPounds` does something other than what its name describes it should not be a member of `vehicle`. – Pete Becker Nov 16 '22 at 00:13
  • On a side note, your `using` statement is in the wrong place, it needs to be after the `#include`s. Though, you really should [avoid `using namespace std;` in the first place](https://stackoverflow.com/questions/1452721/). – Remy Lebeau Nov 16 '22 at 01:16

1 Answers1

2

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.

john
  • 85,011
  • 4
  • 57
  • 81