Virtual Function Polymorphism Implementation In C++ Program

Here we are calculate area of cicle and rectangle using Virtual Functions, it is one of the form of polymorphism, in class shape we are declaring the function area and in class circle and rectangle we are inheriting function from base class shape however polymorphism comes into play when the functions perform different operations, in respective classes.


Program to Implement Virtual Functions In C++ 


#include<stdio.h>
#include<iostream.h>
#include<conio.h>
class shape
{
public:
int length,breadth;
virtual void area()=0; //virtual function
};
class circle:public shape
{
public:
float radius,ans;
void getcircle()
{
  cout<<"enter the radius"<<endl;
  cin>>radius;
}
void area()
{
   ans= 3.14*radius*radius;
   cout<<"area of circle is"<<ans<<endl;
}
};
class rectangle:public shape
{
public:
float ans1,length,breadth;
void getrect()
{
  cout<<"enter the length"<<endl;
  cin>>length;
  cout<<"enter the breadth"<<endl;
  cin>>breadth;
}
void area()
{
   ans1=length*breadth;
   cout<<"area of rectangle= "<<ans1<<endl;
}
};

int main()
{
  clrscr();
  circle ob1;
  rectangle ob2;
  shape *bp;
  bp=&ob1;
  shape *bp1;
  bp1=&ob2;

  ob1.getcircle();
  bp->area();
  ob2.getrect();
  bp1->area();
   getch();
   return 0;
}
/*
enter the radius
2
area of circle is12.56
enter the length
3
enter the breadth
4
area of rectangle= 12
*/

Subscribe to our site to get more such simplified programs.
SHARE

Unknown

  • Image
  • Image
  • Image
  • Image
  • Image
    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment