VIRTUAL
FUNCTIONS:
If there
are member functions with same name in base class and derived class, virtual
functions gives programmer capability to call member function of different
class by a same function call depending upon different context. This feature in
C++ programming is known as polymorphism which is one of the important features
of OOP.
If a base
class and derived class has same function and if you write code to access that
function using pointer of base class then, the function in the base class is
executed even if, the object of derived class is referenced with that pointer
variable.
Example:
#include
<iostream.h>
class
CPolygon
{
public:
int
width, height;
void
set_values (int a, int b)
{
width=a;
height=b;
}
virtual
int area ( )
{
Cout<<”Base
Class Area of CPolygon”;
};
class CRectangle:
public CPolygon
{
public:
int area
(void)
{
return
(width * height);
}
};
class
CTriangle: public CPolygon
{
public:
int area
( )
{
return
(width * height / 2);
}
};
void main
()
{
CRectangle
rect;
CTriangle
trgl;
CPolygon
* ppoly1 = ▭
CPolygon
* ppoly2 = &trgl; ppoly1->set_values (4,5);
ppoly2->set_values (4,5);
cout
<< ppoly1->area( ) << endl;
cout
<< ppoly2->area( ) << endl;
}
Output:
20
10
In this
example class CPolygon includes a virtual function area( ). In this function we
included the cout statement. When the base class pointer have derived class
object and if the pointer points the function area() then the base class area()
function is overloaded with the derived class function area().
Related Topics
Privacy Policy, Terms and Conditions, DMCA Policy and Compliant
Copyright © 2018-2023 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.