C++ program to initialize data members through parameterized constructor for Hierarchical Inheritance

//base class Polygon
//derived classes Rectangle and Triangle

#include <iostream>
using namespace std;
class Polygon
{
    protected:
        int dim1,dim2;
    public:
        Polygon()
        {
            dim1=dim2=0;
        }
        Polygon(int d1,int d2)
        {
            dim1=d1;
            dim2=d2;
        }
};
class Rectangle:public Polygon
{
    public:
        Rectangle(int x,int y):Polygon(x,y)
        {
        }
        int Area()
        {
            return dim1*dim2;
        }
};
class Triangle:public Polygon
{
    public:
        Triangle(int x,int y):Polygon(x,y)
        {
        }
        int Area()
        {
            return 0.5*dim1*dim2;
        }
};
int main()
{
    Rectangle r(4,6);
    cout<<"the area of rectangle is "<<r.Area()<<endl;
    Triangle t(4,8);
    cout<<"the area of triangle is "<<t.Area()<<endl;
    return 0;
}

No comments:

Post a Comment