Polymorphism

Virtual functions and runtime polymorphism

Interview Relevant: Critical OOP concept

Polymorphism

Same interface, different implementations at runtime.

Code Examples

Runtime polymorphism with virtual functions.

cpp
1class Shape {
2public:
3    // Virtual function for runtime polymorphism
4    virtual double area() const {
5        return 0;
6    }
7
8    // Virtual destructor is essential!
9    virtual ~Shape() = default;
10};
11
12class Circle : public Shape {
13    double radius;
14public:
15    Circle(double r) : radius(r) {}
16
17    double area() const override {  // override keyword (C++11)
18        return 3.14159 * radius * radius;
19    }
20};
21
22class Rectangle : public Shape {
23    double w, h;
24public:
25    Rectangle(double w, double h) : w(w), h(h) {}
26
27    double area() const override {
28        return w * h;
29    }
30};
31
32// Polymorphic behavior
33void printArea(const Shape& s) {
34    cout << s.area() << endl;  // Calls correct version
35}
36
37Circle c(5);
38Rectangle r(3, 4);
39printArea(c);  // 78.5398
40printArea(r);  // 12
41
42// Virtual function table (vtable)
43// - Each polymorphic class has a vtable
44// - Each object has a vptr pointing to its vtable
45// - Virtual calls look up function in vtable

AI Tutor

Ask about the topic

Sign in Required

Please sign in to use the AI tutor

Sign In