Multiple Inheritance in C++ with Example Program

...
Multiple-Inheritance-in-C++-with-diagramInheritance is the capability of one class to inherit properties from another class. The class it's properties are inherited is called Base Class, that means Base Class is the class whose properties are inherited by another class, we can also call the Base class as Super Class. And the class to which the properties of the Base Class is inherited is called Derived Class or Sub Class. There are different forms of inheritance, they are Single Inheritance, Multiple Inheritance, Hierarchical Inheritance, Multilevel Inheritance and Hybrid Inheritance. Let's learn what is Multiple Inheritance in C++ here.

Multilevel Inheritance is an inheritance hierarchy wherein one derived class inherits from multiple Base Classes.

Sample Program Using Multiple Inheritance in C++

Diagram-of-Multiple-Inheritance-on-C++Here is an example of implementing Multiple Inheritance in C++. The below source code can calculate Area and Perimeter of a Rectangle. In this code we have three classes they are Rectangle_Area, Rectangle_Perimeter, Rectangle_Data. Rectangle_Data class is derived from classes Rectangle_Area and Rectangle_Perimeter.

When a user run the program the user is asked for the length and breadth of the rectangle he has. And the values given by the user are passed and assigned to variable 'l' and 'b', so the equations can now calculate the perimeter as well as the area.
#include <iostream>
using namespace std;
class Rectangle_Area
{
  public:
    float calculate_area(float l,float b)
    {
        return l*b;
    }
};

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

/* Rectangle_Data class is derived from classes Rectangle_Area and Rectangle_Perimeter. */
class Rectangle_Data : private Rectangle_Area, private Rectangle_Perimeter
{
    private:
        float length, breadth;
    public:
       Rectangle_Data() : length(0.0), breadth(0.0) { }
       void get_data( )
       {
           cout<<"Please Provide length: ";
           cin>>length;
           cout<<"Please Provide Width: ";
           cin>>breadth;
       }

       float calculate_area()
       {
       /* Calling calculate_area() of class Rectangle_Area and returning it. */

           return Rectangle_Area::calculate_area(length,breadth);
       }

       float calculate_Perimeter()
       {
       /* Calling calculate_perimeter() function of class Rectangle_Perimeter and returning it. */ 

           return Rectangle_Perimeter::calculate_perimeter(length,breadth);
       }
};

int main()
{
    Rectangle_Data r;
    r.get_data();
    cout<<"Area = "<<r.calculate_area();
    cout<<"\nPerimeter = "<<r.calculate_perimeter();
    return 0;
}
Out Put
Please Provide length: 3.5
Please Provide Width: 8.2
Area= 28.7
Perimeter= 23.4
Did this help you? Please share your experience here.

...

0 comments:

Post a Comment