Polymorphism
Virtual Functions
- Definition: A function that gets called based on the object's type rather than the pointer/reference type during upcasting
- Purpose: Enables runtime polymorphism (dynamic method dispatch)
- Declaration: Use
virtual
keyword in the base class
- Polymorphic class: Any class with at least one virtual function
- Inheritance of virtual property: If a base class function is virtual, the derived class function with the same signature is automatically virtual
Function Overriding Rules
- Function must exist in both base and derived classes (different scopes)
- Signatures (including return type) must be identical
- The base class function must be virtual
Binding Mechanisms
- Early Binding (Static/Compile-time):
- Function calls resolved at compile time
- Occurs when calling any function on an object
- Occurs when calling non-virtual functions on pointers/references
- Late Binding (Dynamic/Runtime):
- Function calls resolved at runtime
- Occurs when calling virtual functions on pointers/references
- Enables polymorphic behavior
Virtual Function Implementation (vptr and vtable)
- vtable (Virtual Function Table):
- Created per class with virtual functions
- Array of function pointers to virtual functions
- Compiler-generated data structure
- vptr (Virtual Function Pointer):
- Implicit pointer added to objects of classes with virtual functions
- Points to the class's vtable
- Usually positioned at the start of the object
- Added once per object
- Automatically managed by the compiler
- Increases object size by 2/4/8 bytes depending on the architecture
- Memory Impact: Size of object = size of non-static data members + vptr size (if the class has virtual functions)
Virtual Function Design Guidelines
- Non-virtual function: When base class implementation is 100% complete