Virtual Function

In Object Oriented Programming, a virtual function or method is a function whose behavior can be overridden within an inheriting class by a function with the same signature. This concept is important part of polymorphism.
Virtual function allows a program to call methods that don't necessarily even exist at the moment code is compiled.
In C++, virtual methods are declared by prepending the function with the virtual keyword in the base class. This modifier is inherited by all implementations of that method in derived classes, meaning that they can continue to over-ride each other and be late-bound.
For example, a base class Animal could have a virtual function eat. Subclass Fish would implement eat()differently than subclass Wolf, but one can invoke eat() on any class instance referred to as Animal, and get the eat() behavior of the specific subclass.pure virtual function or pure virtual method is a virtual function that is required to be implemented by a derived class, if that class is not abstract. Classes containing pure virtual methods are termed "abstract" and they cannot be instantiated directly. A subclass of an abstract class can only be instantiated directly if all inherited pure virtual methods have been implemented by that class or a parent class. Pure virtual methods typically have a declaration (signature) and no definition (implementation).
A virtual function depends on a "vtable" or "virtual table". If any function of the class is declared to be virtual, a vtable is constructed which stores the addresses of virtual function of this class. The compiler also adds a hidden vptr variable in all such classes which points to the vtable of that class. If virtual function is not overridden in any of 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 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.
In C++, non-virtual functions calls are resolved at compile time with static binding while the virtual functions are resolved at run time with dynamic binding.

Comments

Popular posts from this blog

Three mislabeled Jar

Difference between Macro And function