Polymorphism
Virtual Functions
Member function in a class that you expect to be defined in derived classes
- 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 function
class Base {
public:
virtual void show() {
cout << "Base show" << endl;
}
};
class Derived : public Base {
public:
void show() override { // 'override' is optional but good practice
cout << "Derived show" << endl;
}
};
int main() {
Base *bPtr;
Derived d;
bPtr = &d;
// This will call Derived::show() because it's a virtual function
bPtr->show();
return 0;
}
- Dynamic Binding (Late Binding): When a virtual function is called on an object, the type of the object is looked up at runtime, and the corresponding function in the object's actual class is called. This is opposed to static binding (early binding), where the function call is resolved at compile time.
- Base Class Pointer/Reference: If you have a pointer or reference to a base class, you can use it to call a virtual function and execute the derived class's version of the function.
- Virtual Table (vtable): When a class contains virtual functions, the compiler creates a hidden table known as the virtual table. Each object of the class contains a pointer to its class's virtual table. When a virtual function is called, the corresponding function address in the virtual table is looked up at runtime.
- Virtual Destructor: It's important to declare destructors as virtual in base classes if you're doing polymorphic behavior with base class pointers. This ensures that the derived class's destructor gets called, which is essential for proper resource cleanup.