Friday, February 5, 2010

Virtual and Pure Virtual Functions in C++

When we use the same function name in both the base and derived classes, the function in base class is declared as Virtual using the keyword "virtual" preceding its normal declarations.
when a function is made virtual, C++ determines which function to use at run time based on the type of object pointed to by the base pointer, rather then the type of the pointer.Thus, by making the base pointer to point to different objects, we can execute different versions of the of the virtual function.
Example :
#include
using namespace std;
class Base
{
public:
void display() {cout<<"\nDisplay base"; }
virtual void show() {cout<<"\nShow Base";}
};
class Derived:public Base
{
public:
void display() {cout<<"\nDisplay Derived";}
void show() {cout<<"\nShow Derived";}
};
int main()
{
Base B;
Derived D;
Base *bptr;

cout<<"\nbptr points to Base \n";
bptr=&B;
bptr->display(); //calls Base version...
bptr->show(); //calls Base version...

cout<<"\n\n bptr points to Derived \n";
bptr=&D;
bptr->display(); //calls Base version...
bptr->show(); //calls Derived version...

return 0;
}
The output of following program would be:
bptr points to Base

Display base
Show base

bptr points to Derived

Display base
show derived

NOTE: when bptr is made to point to the object D, the statement
bptr->display(); calls only the function associated with the Base(i.e Base::display()), whereas the statement
bptr->show(); calls the Derived version of show(). This is because the function display() has not been made virtual in Base class.

Pure Virtual Functions
It is normal practice to declare a function virtual inside the base class and redefine it in the derived classes. The function inside the base class is seldom used for performing any task. It only serves as a placeholder. For example:
class Base
{
public:
virtual void display() { } //empty virtual function........
};
class Derived:public Base
{
public:
void display()
{
/* Some data to display */
}
};
the function display() in Base class has been defined 'empty'. Such functions are called "do-nothing" functions.
A "do-nothing" function may be defined as follows:

virtual void display() = 0;
Such functions are called pure virtual functions. A pure virtual function is a function declared in a base class that has no definition relative to the base class.In such cases, the compiler requires each derived class to either define the function or redeclare it as a pure virtual function. Remember that a class containing pure virtual functions cannot be used to declare any objects of its own. Such classes are called abstract base classes.