Header Ads

Some of the fact of Virtual Function in C++


Here are some of the characteristics of the virtual methods according to my understanding.

If we declare the virtual method in the base class it will automatically make the method in derived as a virtual. No need to declare it as virtual in derived class.

If virtual method will invoke or call the by reference or pointer to object then it will call the method defined for the object type rather than defined for reference or pointer type.

Calling Method or function is decided at run time rather than compile time in dynamic binding. 

Frequently used when base class pointer point to derived class pointer. 

If the method is declared as virtual then we have to redefine the method in derived class. (Function overloading)

The run-time selection is the primary /main advantage of the virtual method.

Consume more memory than normal nonvirtual function.

Slower in response compare to nonvirtual function.

The virtual function uses the vtable entry lookup to resolve the function call issue at the run time. 

Overhead becomes very high if virtual function / method called frequently. It will increase the size of Object and size of the pointer to the vtable. 

Virtual functions typically represent the integer offset to a virtual table (vtable). So changing order, adding, removing will change this offset. So adding, removing or reordering or virtual function needs recompilation to confirm the calling of right function.