How do virtual functions work in C++?

A virtual function depends on a “vtable” or “Virtual Table.” If any function of a class is declared to be virtual, a vtable is constructed which stores addresses of the virtual functions of this class. The compiler also adds a hidden vptr variable in all such classes which points to the vtable of that class. If  a virtual function is not overridden in the derived class, the vtable of the derived class stores the address of the function in its parent class. The vtable is used to resolve the address of the function when the virtual function is called. Dynamic binding in C++ is performed through the vtable mechanism.

Thus, when we assign the derived class object to the base class pointer, the vptr variable points to the vtable of the derived class. This assignment ensures that the most derived virtual function gets called.

Consider the following code.

C++:
01 class Shape{
02   public:
03   int edge_length;
04   virtual int circumference(){
05     cout<<“Circumference of Base Class\n;
06     return 0;
07   }
08 };
09 
10 class Triangle:public Shape{
11   public:
12   int circumference(){
13     cout<<“Circumference of Triangle Class\n;
14     return 3*edge_length;
15   }
16 };
17 
18 void main(){
19   Shape* x=new Shape();
20   x->circumference();
21   Shape* y=new Triangle();
22   y->circumference();
23 }
In the previous example, circumference is a virtual function in the Shape class, so it becomes virtual in each of the derived classes(Triangle, etc). C++ non-virtual function calls are resolved at compile time with static binding, while virtual function calls are resolved at run time with dynamic binding.
Advertisements
This entry was posted in C++. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s