The C++ multi-inheritance where a derived class inherited from two base classes code example


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: Printing some data from the two base classes through the inherited class of the C++ multi-inheritance programming

To show: How a derived/inherited class inherit from two base classes in C++ programming




// another simple multiple inheritance C++ program example

#include <iostream>

using namespace std;


// class declaration and implementation

// base class

class Base1



int SampleDataOne;




SampleDataOne = 100;



int SampleFunctOne()


return SampleDataOne;




// another base class

class Base2



int SampleDataTwo;




SampleDataTwo = 200;



int SampleFunctTwo()


return SampleDataTwo;




// derived class

class Derived1:public Base1,public Base2


int MyData;




MyData = 300;



int MyFunct()


// the protected data of the base classes are available for this derived/inherited class

return (MyData + SampleDataOne + SampleDataTwo);




// main program

int main(void)


// instantiate objects

Base1 SampleObjOne;

Base2 SampleObjTwo;

Derived1 SampleObjThree;


cout<<"Normal access Base1 class data: "<<SampleObjOne.SampleFunctOne()<<endl;

cout<<"Normal access Base2 class data: "<<SampleObjTwo.SampleFunctTwo()<<endl;

cout<<"Normal access Derived1 class data: "<<SampleObjThree.MyFunct()<<endl<<endl;

cout<<"Inherited Base1 class data by Derived1 derived class:"<<endl;

cout<<"Base1 class data: "<<SampleObjThree.Base1::SampleFunctOne()<<endl;

cout<<"Inherited Base2 class data by Derived1 derived class:"<<endl;

cout<<"Base2 class data: "<<SampleObjThree.Base2::SampleFunctTwo()<<endl;


return 0;



Output example:


Normal access Base1 class data: 100

Normal access Base2 class data: 200

Normal access Derived1 class data: 600

Inherited Base1 class data by Derived1 derived class:

Base1 class data: 100

Inherited Base2 class data by Derived1 derived class:

Base2 class data: 200

Press any key to continue . . .



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