Semester : SEMESTER 6
Subject : Object Oriented Programming
Year : 2018
Term : MARCH
Scheme : 2015 Full Time
Course Code : EC 312
Page:15
They are mainly used to achieve Runtime polymorphism
Functions are declared with a virtual keyword in base class. * The resolving of function
call is done at Run-time.
Rules for Virtual Functions
They Must be declared in public section of class.
Virtual functions cannot be static and also cannot be a friend function of another class.
Virtual functions should be accessed using pointer or reference of base class type to achieve run
time polymorphism.
The prototype of virtual functions should be same in base as well as derived class.
They are always defined in base class and overridden in derived class. It is not mandatory for
derived class to override (or re-define the virtual function), in that case base class version of
function is used.
A class may have virtual destructor but it cannot have a virtual constructor.
Compile-time(early binding) VS run-time(late binding) behavior of Virtual
Functions
Consider the following simple program showing run-time behavior of virtual functions.
// CPP program to illustrate
// concept of Virtual Functions
#include
namespace std;
class base
public:
virtual voidprint ()
{ cout<< "print base class" ೪೮೮೧೮1; }
void show ()
{ cout<< "show base class" <
class derived:public base
public: void
print ()
{ cout<< "print derived class" <
voidshow ()