C++ program to use base class pointer to call derived class' member function

//base class Polygon with two dimensions
//Derived classes Rectangle and Triangle to calculate Area()

#include <iostream>
using namespace std;
class Polygon
{
    protected:
        int dim1,dim2;
    public:
        void readData()
        {
            cout<<"Enter dimensions:";
            cin>>dim1>>dim2;
        }
};
class Rectangle:public Polygon
{
    public:
        int Area()
        {
            return dim1*dim2;
        }
};
class Triangle:public Polygon
{
    public:
        int Area()
        {
            return (dim1*dim2/2);
        }
};
int main()
{
    Polygon *p;
    Rectangle r;
    cout<<endl<<"For rectangle:"<<endl;
    r.readData();
    p=&r;
    cout<<"Area of rectangle is "<<((Rectangle*)p)->Area();
    Triangle t;
    cout<<endl<<"For triangle:"<<endl;
    t.readData();
    p=&t;
    cout<<"Area of triangle is "<<((Triangle*)p)->Area();
   return 0;
}

No comments:

Post a Comment