Virtual Functions and the vtable
Implement runtime polymorphism with virtual functions and inspect the vtable concept.
Static vs Dynamic Binding
By default, member calls are statically bound — the compiler picks the function based on the declared type. With virtual functions, the call is dynamically bound based on the actual type.
Declaring a virtual Function
Mark the function virtual in the base class. Derived classes can override it.
class Shape {
public:
virtual double area() const = 0; // pure virtual
virtual ~Shape() = default;
};
class Circle : public Shape {
double r_;
public:
Circle(double r) : r_(r) {}
double area() const override { return 3.14159 * r_ * r_; }
};All lessons in this course
- Single and Multiple Inheritance
- Virtual Functions and the vtable
- Abstract Classes and Pure Virtual Methods
- Inheritance vs Composition Trade-offs