Multilevel Inheritance is an inheritance hierarchy wherein one derived class inherits from multiple Base Classes.
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.
Sample Program Using Multiple Inheritance in 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 PutPlease Provide length: 3.5 Please Provide Width: 8.2 Area= 28.7 Perimeter= 23.4Did this help you? Please share your experience here.
...
0 comments:
Post a Comment