A virtual function is a member function declared in a base class using the virtual keyword and overridden in a derived class. Virtual functions enable runtime polymorphism, where the function call is resolved at runtime based on the actual object type, not the pointer or reference type.
Runtime polymorphism is achieved through late binding, allowing different behaviors for the same function call in an inheritance hierarchy.
The correct derived class function is invoked based on the actual object.
Virtual destructors ensure proper cleanup when deleting derived objects via base pointers.
Why Virtual Destructors Are Important
When deleting objects through a base class pointer, destructors must be virtual.
This prevents memory leaks and ensures derived destructors are executed.
Real-Life Example: Employee Management System
Consider employee management system where a base class Employee defines virtual functions such as raiseSalary() and promote(), which are overridden by derived classes like Manager or Engineer. This allows operations to be performed on a list of employees while the correct behavior is selected at runtime without knowing the specific employee type.
Explanation:
Employee* can point to any derived employee type.
raiseSalary() is resolved at runtime.
The correct function is executed without knowing the actual employee type.
This makes the system flexible, extensible, and maintainable.
Internal Working of Runtime Resolution
The compiler uses two internal mechanisms:
vtable: A table of function pointers, maintained per class.
vptr: A pointer to vtable, maintained per object instance.