C++ multi-inheritance code example demonstrating the variable overriding and function/method overloading of the derived/inherited class

 

Compiler: Visual C++ Express Edition 2005

Compiled on Platform: Windows XP Pro SP2

Header file: Standard

Additional library: none/default

Additional project setting: Set project to be compiled as C++

Project -> your_project_name Properties -> Configuration Properties -> C/C++ -> Advanced -> Compiled As: Compiled as C++ Code (/TP)

Other info: none

To do: Deriving the variable and function/method from the based classes and overriding and overloading them respectively in C++ multi inheritance programming

To show: How to override the base class variables and overloading the based class function/method by the inherited/derived class in C++ multi inheritance programming

 

#include <iostream>

using namespace std;

 

// class declaration and implementation

// moving_van base class

class moving_van

{

// these variables only available for derived class because of the protected keyword

protected:

double payload;

double gross_weight;

double mpg;

 

public:

void initialize(double pl, double gw, double input_mpg)

{

payload = pl;

gross_weight = gw;

mpg = input_mpg;

};

 

double efficiency(void)

{

return (payload / (payload + gross_weight));

};

 

double cost_per_ton(double fuel_cost)

{

return (fuel_cost / (payload / 2000.0));

};

};

 

// driver base class

class driver

{

protected:

double hourly_pay;

 

public:

void initialize(double pay)

{

hourly_pay = pay;

};

 

double cost_per_mile(void)

{

return (hourly_pay / 55.0);

};

};

 

// derived class

// inherit from two different base classes

class driven_truck : public moving_van, public driver

{

public:

void initialize_all(double pl, double gw, double input_mpg, double pay)

{

payload = pl;

gross_weight = gw;

mpg = input_mpg;

hourly_pay = pay;

};

 

double cost_per_full_day(double cost_of_gas)

{

return ((8.0 * hourly_pay) + (8.0 * cost_of_gas * 55.0) / mpg);

};

};

 

// main program

int main(void)

{

// instantiate an object

driven_truck john_merc;

 

// override the constructor values if any

john_merc.initialize_all(20000.0, 12000.0, 5.2, 12.50);

 

cout<<"The efficiency of the Merc truck is "<<john_merc.efficiency()<<" %\n";

cout<<"The cost per mile for John to drive Merc is $"<<john_merc.cost_per_mile()<<"\n";

cout<<"The cost per day for John to drive Merc is $"<<john_merc.cost_per_full_day(1.129)<<"\n";

 

return 0;

}

 

Output example:

 

The efficiency of the Merc truck is 0.625 %

The cost per mile for John to drive Merc is $0.227273

The cost per day for John to drive Merc is $195.531

Press any key to continue . . .

 

 

 

C and C++ Programming Resources | C & C++ Code Example Index