Create classes as given in the figure . Find the area of circle ,triangle, rectangle,square.
Objective
Write a C++ program to demonstrate Hierarchical Inheritance with different shapes.
Algorithm / Approach
- Create a single base
class Shapecontaining common area calculation logic (areaCircle,areaRec,areaTri). - Create three derived classes:
Rectangle,Circle, andTriangle. All three inherit directly fromShape. - Inside each derived class, ask for the specific dimensions needed and call the inherited calculation function from the base class.
main.cpp
#include<iostream>
using namespace std;
class Shape {
int ar;
public:
void areaCircle(int a) {
ar = 3.14*a*a;
cout<<"Area of Circle = "<< ar<< endl;
}
void areaRec(int a, int b) {
ar = a*b;
cout<<"Area of Rectangle "<< ar<< endl;
}
void areaTri(int a, int b) {
ar = a*b/2;
cout<<"Area of Triangle "<< ar<< endl;
}
};
class Rectangle :public Shape {
public :
int l,b;
void input() {
cout<<"Enter Length , Breadth : ";
cin>>l>>b;
areaRec(l,b);
}
};
class Circle : public Shape {
public:
int r;
void input() {
cout<<"Enter Radius : ";
cin>>r;
areaCircle(r);
}
};
class Triangle : public Shape {
public :
int b,h;
void input() {
cout<<"Enter Base,Height : ";
cin>>b>>h;
areaTri(b,h);
}
};
int main() {
Rectangle r;
r.input();
Triangle t;
t.input();
Circle c;
c.input();
return 0;
}
Expected Output
Enter Length , Breadth : 4 5 Area of Rectangle 20 Enter Base,Height : 5 4 Area of Triangle 10 Enter Radius : 7 Area of Circle = 153
Explanation of the Program
- Hierarchical Inheritance is when multiple different child classes inherit from exactly ONE parent class (a "one-to-many" relationship).
- Here, Rectangle, Circle, and Triangle are completely unrelated to each other, but they all share the common traits and functions provided by the single
Shapeparent.
Complexity
Time Complexity
O(1)
Space Complexity
O(1)