Topic 58 of 83
Runtime Poly
Overview
Run-time polymorphism is achieved using `virtual` functions and pointers/references. It decides which function to execute during execution time (Late Binding) by looking up a vtable.
Syntax
cpp
class Base {
public:
virtual void show() { cout << "Base"; } // VIRTUAL enables overriding
};
class Derived : public Base {
public:
void show() override { cout << "Derived"; } // OVERRIDE is good practice
};
// Usage
Base* b = new Derived();
b->show(); // Output: Derived (resolved at runtime!)Common Pitfalls
- Forgetting the `virtual` keyword in the base class. If omitted, the compiler uses Early Binding, and `b->show()` would print 'Base' instead of 'Derived'.
Interview Tips
- Explain the 'vtable' (virtual table). Every class with virtual functions has an invisible array of function pointers created by the compiler. Objects contain a hidden 'vptr' pointing to this table, which is used to look up the correct function at runtime.
- Always mark base class destructors as `virtual` to prevent memory leaks when deleting derived objects via a base pointer.
Real-World Example
Managing a mixed collection of UI elements.
example
cpp
#include <iostream>
#include <vector>
using namespace std;
class UIControl {
public:
virtual void render() { cout << "Rendering basic control\n"; }
virtual ~UIControl() {} // Essential!
};
class Button : public UIControl {
public:
void render() override { cout << "Rendering Button\n"; }
};
class TextField : public UIControl {
public:
void render() override { cout << "Rendering TextField\n"; }
};
int main() {
vector<UIControl*> screen;
screen.push_back(new Button());
screen.push_back(new TextField());
for (UIControl* c : screen) {
c->render(); // Dynamically calls correct render()
delete c;
}
return 0;
}