How to find the area of a rectangle and triangle using a derived class rectangle and a derived triangle from the base class polygon (Inheritance in c++ ?
Zaarm Tech Selected answer as best November 20, 2021
#include<iostream.h>
#include<conio.h>
class Polygon
{
protected:
int width, height;
public:
void set_values(int a, int b)
{
width = a;
height = b;
}
};
class Rectangle: public Polygon
{
public:
int area()
{
return (width * height);
}
};
class Triangle: public Polygon
{
public:
int area()
{
return (width * height/2);
}
};
void main()
{
Rectangle r;
Triangle t;
clrscr();
r.set_values(4,5);
t.set_values(5,10);
cout<<“Area of Rectangle = “<<r.area()<<endl;
cout<<“Area of triangle = “<<t.area();
getch();
}
The objects of the classes Rectangle and Triangle each contain members inherited from Polygon. These are: width, height and set_values(). The protected access specifier is similar to private. Its only difference occurs in fact with inheritance. When a class inherits from another one, the members of the derived class can access the protected members inherited from the base class, but not its private members. Since we wanted width and height to be accessible from members of the derived classes Rectangle and Triangle and not only by members of Polygon, we have used protected access instead of private.
Zaarm Tech Selected answer as best November 20, 2021