Virtual Functions
We know that when a base class pointer refers to a derived class object, the extra features in derived class are not available. To access the extra features in the derived class, we make the functions in the base class as virtual. Syntax for creating a virtual function is as follows:
1
2
3
4
5
|
virtual return–type function–name(params–list)
{
//Body of function
...
}
|
A class which contains one or more virtual functions is known as a polymorphic class. Following program demonstrates accessing derived class features using virtual functions:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
|
#include<iostream>
using namespace std;
class A
{
protected:
int x;
public:
virtual void show() //virtual function
{
cout<<“x = “<<x<<endl;
}
};
class B : public A
{
protected:
int y;
public:
B(int x, int y)
{
this->x = x;
this->y = y;
}
void show()
{
cout<<“x = “<<x<<endl;
cout<<“y = “<<y<<endl;
}
};
int main()
{
A *bptr;
B objB(30, 20);
bptr = &objB;
bptr->show();
return 0;
}
Output of the above program is as follows:
x = 30
y = 20
|
Rules for Virtual Functions
Following points must be remembered while working with virtual functions:
- Virtual functions must be members of a class.
- Virtual functions must be created in public section so that objects can access them.
- When virtual function is defined outside the class, virtual keyword is required only in the function declaration. Not necessary in the function definition.
- Virtual functions cannot be static members.
- Virtual functions must be accessed using a pointer to the object.
- A virtual function cannot be declared as a friend of another class.
- Virtual functions must be defined in the base class even though it does not have any significance.
- The signature of virtual function in base class and derived class must be same.
- A class must have a virtual destructor but it cannot have a virtual constructor.
Pure Virtual Functions
When the code for virtual function in a base class is insignificant, we can make such virtual functions as pure virtual functions. A pure virtual function is a virtual function without any definition. Syntax for creating a pure virtual functions is as follows:
virtual return-type function-name(params-list) = 0;
A class which contains at least one pure virtual function is called a abstract class and the class which provides the definition for the pure virtual function is called a concrete class.
Late Binding (Dynamic Polymorphism)
In inheritance when a derived class object is assigned to a base class pointer, and a polymorphic function is invoked, the function call is linked to the function definition at run-time. Such postponement of linkage to run-time instead of compile-time is called as late binding or dynamic polymorphism.’