0

Inheritence Problem

The given code gives error #include <iostream> #include <string.h> using namespace std; class Vehicle; class Honda; class Civic; class Vessel; class CD150; class Vehicle{ public: int VModel; string VColor; int NOfDoors; int NOfTires; public: Vehicle(int VM,string vC,int nD,int nT){ VModel = VM; VColor = vC; NOfDoors = nD; NOfTires = nT; } int SpeedPerMile(int speed){ return speed; } void BrakeSystem(string brakes){ cout << brakes; } }; //Honda Class class Honda:Vehicle{ private: string ChassasNo; public: Honda(string ChNo){ ChassasNo = ChNo; cout << ChassasNo; } }; int main(){ //Somw Details of main Vehicle Class Vehicle v(572,"Red",4,4); v.SpeedPerMile(100); v.BrakeSystem("genuine"); Honda h("Sel175"); }

15th Apr 2020, 12:02 PM
Saad Saleem
Saad Saleem - avatar
4 Answers
+ 2
When instantiating a derived class, first the constructor of the base class is called. If there is no explicit call to a base class constructor, the default constructor accepting no parameters is assumed. However, your vehicle class contains no default constructor, only one with four parameters, which you do not call in the "Honda" constructor, hence the compiler tries to find the definition for a constructor that does not exist (error: no matching function...). There are two ways to fix this: 1. Add a default constructor to your "Vehicle" class that initializes the member variables to some values. You can implement it yourself or delegate it to the compiler via Vehicle() = default; 2. Expand the "Honda" constructor to additionally accept all parameters the "Vehicle" constructor would expect, and pass them to the base class constructor, i.e. Honda( ..., string ChNo ) : Vehicle( ... ) { ChassasNo = ChNo; }
15th Apr 2020, 1:13 PM
Shadow
Shadow - avatar
15th Apr 2020, 12:21 PM
Saad Saleem
Saad Saleem - avatar
15th Apr 2020, 12:22 PM
Saad Saleem
Saad Saleem - avatar
0
Shadow Thanks Superb explanation
15th Apr 2020, 4:27 PM
Saad Saleem
Saad Saleem - avatar