-3
class car
{
    string carID
    string carName
};

class electric : public car
{
    string battery
    string model
};

base class is car. electric is a derived class that inherits from car. What would need to be included in the constructor to initialise them and then set the values when the user inputs a new car with the data for all the attributes?

relaxxx
  • 7,566
  • 8
  • 37
  • 64

3 Answers3

1

You need to define constructors and subsequently use them properly. During initialization of a derived class, you should always call the appropriate constructor of the base class:

Derived::Derived(...):Base(...),<optional initizaliation of Derived members>{...}

For example:

class car
{
    string carID;
    string carName;
public:
    car(string carid, string carname):carID(carid),carName(carname){}
};

class electric : public car
{
    string battery;
    string model;
public:
    electric(string carid, string carname, string battery, string model)
    :car(carid,carname),battery(battery),model(model){}
};
Marc Claesen
  • 16,778
  • 6
  • 27
  • 62
  • thank you for your reply. How would i define the set function to set the values of a particular electric car, will i have to call the car constructor then the electric? – user2355449 May 06 '13 at 17:26
  • No, you always call the derived class constructor. As you can see in the code example I listed, the derived class's constructor calls the base class constructor during initialization. – Marc Claesen May 06 '13 at 17:29
  • You're welcome, if it is clear to you now, please mark this question as answered. – Marc Claesen May 06 '13 at 17:34
0

In your current model, you actually can't access any of the fields of car, because by default in C++ when using the class keyword, all fields are private. They need to be protected or public in order for a sub-class to access them.

Kevin Anderson
  • 6,850
  • 4
  • 32
  • 54
0

You should initialize base class members by calling the base class constructor at the derived class's constructor initialization list.

 class car
 {
    string carID
    string carName
    public:
       car (string id, string name): carID(id), carName(name) {}
 };

 class electric : public car
 {
   string battery
   string model
   public:
      electric (string id, string name, string b, string m): car(id, name), 
                                                battery(b), model(m){}
 };
taocp
  • 23,276
  • 10
  • 49
  • 62