C++ program to implement Run Time Polymorphism with Virtual Function

//base class Shape with dim as data member and constructor to initialize its data
//derived classes Square and Circle to FindPerimeter() as member functions
//dim as side for Square and dim as radius for Circle
//Implement Run Time Polymorphism

#include <iostream>
using namespace std;
class Shape
{
    protected:
        float dim;
    public:
        Shape()
        {
            dim=0;
        }
        Shape(float d)
        {
            dim=d;
        }
        virtual float FindPerimeter()
        {
            return 0.0;
        }
};
class Square:public Shape
{
    public:
        Square(float d):Shape(d)
        {
        }
        float FindPerimeter()
        {
            return 4*dim;
//P=4*l;
        }
};
class Circle:public Shape
{
    public:
        Circle(float d):Shape(d)
        {
        }
        float FindPerimeter()
        {
            return 2*3.1416*dim;
//P=2*PI*r;
        }
};
int main()
{
    Square s(5);
    Circle c(7);
    Shape *sh;
    sh=&s;
    cout<<"Area of Square is "<<sh->FindPerimeter()<<endl;
    sh=&c;
    cout<<"Area of Circle is "<<sh->FindPerimeter()<<endl;
    return 0;
}

No comments:

Post a Comment