CPP Multiple Inheritance

Multiple Inheritance

  • Multiple Inheritance is a feature of C++ where a class can inherit from more than one classes.
  • In this type of inheritance a single derived class may inherit from two or more than two base classes.
  • The constructors of inherited classes are called in the same order in which they are inherited.

Example:

#include <iostream>

class Area
{
  public:
    float area_calc(float l,float b)
    {
        return l*b;
    }
};

class Perimeter
{
  public:
    float peri_calc(float l,float b)
    {
        return 2*(l+b);
    }
};

/* Rectangle class is derived from classes Area and Perimeter. */
class Rectangle : private Area, private Perimeter
{
    private:
        float length, breadth;
    public:
       Rectangle() : length(0.0), breadth(0.0) { }
       void get_data( )
       {
           cout<<"Enter length: ";
           cin>>length;
           cout<<"Enter breadth: ";
           cin>>breadth;
       }

       float area_calc()
       {
       /* Calls area_calc() of class Area and returns it. */

           return Area::area_calc(length,breadth);
       }

       float peri_calc()
       {
       /* Calls peri_calc() function of class Perimeter and returns it. */ 

           return Perimeter::peri_calc(length,breadth);
       }
};

void main()
{
    Rectangle r;
    r.get_data();
    cout<<"Area = "<<r.area_calc();
    cout<<"\nPerimeter = "<<r.peri_calc();
    getch();
}

Output:

Enter length: 5.1
Enter breadth: 2.3
Area = 11.73
Perimeter = 14.8


Share This Page to Download:

Share to Download

Share This Page on:


Ask Question