Program Demonstrates Multiple Inheritance In Which A Class Is Derived Publicly From Both The Base Classes In C++

LEVEL: Beginner

Whats in this post?

  1. Code
  2. Output
  3. Background and Explanation of the code

Code


To copy code: Click View Source “View Source” on the right of this code snippet.


Background and Explanation of the code


In this program we define a class base1 containing a protected data member x and public member functions readx ( ) and showx ( ) for inputting and displaying value of x.Similarly another class base2 is defined that contains a data member y and two public member functions ready ( )and showy ( ).The clas der is inherited from both the base classes base1 and base2 publicly through multiple inheritance .As the class der is derived publicly from both the base class base1 and base2 so the object of derive class can access public members of base1 and base2 in the main ( ).In the main() the statement d1.readx ( ); invokes the member function readx ( ) of the base1 class for inputting value of x.Similarly the statement d1.raedy ( ); invokes the ready ( ) of base2 for inputting value of y.The statement d1.add ( ); invokes the member function add ( ) of the der class to perform addition of values of protected data members x and y as they can be accessed directly in the der class.The remaining statement display the values of x, y and z.

OUTPUT

Enter value of x :   20

Enter value of y :   30

x  =  20

y  =  30

z   =   50