What do you mean by Pure Virtual function?
A pure virtual function has no definition related to the base class. Only the function prototype is included to make a pure virtual function the following syntax is used:
virtual return_type function_name(par_list) = 0;
The following is an example program:
Program Code:
#include<iostream>
using namespace std;
// definition of base class area
class area
{
double x,y;
public:
void set_area(int a,int b) // definition of member function of class area
{
x=a;
y=b;
}
void get_dim(double &a,double &b) // definition of member function of class area
{
a=x;
b=y;
}
virtual double get_area()=0; // declaration of pure virtual function
};
// definition of derived class rectangle
class rectangle : public area
{
public:
double get_area() // definition of pure virtual function in derived class rectangle
{
double a,b;
get_dim(a,b);
return a*b;
}
};
class triangle : public area
{
public:
double get_area() // definition of pure virtual function in derived class triangle
{
double a,b;
get_dim(a,b);
return 0.5*a*b;
}
};
// definition of main() function
int main()
{
area *p;
rectangle r;
triangle t;
r.set_area(3,4);
t.set_area(4,5);
p=&r;
cout<<"Area of rectangle is : "<<p->get_area();
cout<<endl;
p=&t;
cout<<"Area of triangle is : "<<p->get_area();
cout<<endl;
return 0;
}
The program output is tested on www.jdoodle.com
Output:
Area of rectangle is : 12
Area of triangle is : 10
Thanks
Mukesh Rajput





Post A Comment:
0 comments: