Limitations of Virtual Functions

  • Slower: The function call takes slightly longer due to the virtual mechanism and makes it more difficult for the compiler to optimize because it does not know exactly which function is going to be called at compile time.
  • Difficult to Debug: In a complex system, virtual functions can make it a little more difficult to figure out where a function is being called from.


Virtual Function in C++

A virtual function (also known as virtual methods) is a member function that is declared within a base class and is re-defined (overridden) by a derived class. When you refer to a derived class object using a pointer or a reference to the base class, you can call a virtual function for that object and execute the derived class’s version of the method.

  • Virtual functions ensure that the correct function is called for an object, regardless of the type of reference (or pointer) used for the function call.
  • They are mainly used to achieve Runtime polymorphism.
  • Functions are declared with a virtual keyword in a base class.
  • The resolving of a function call is done at runtime.

Similar Reads

Rules for Virtual Functions

The rules for the virtual functions in C++ are as follows:...

Working of Virtual Functions (concept of VTABLE and VPTR)

...

Limitations of Virtual Functions

As discussed here, if a class contains a virtual function then the compiler itself does two things....