C++ Polymorphism
| Compile-time | Run-time |
|---|---|
| Function overloading, operator overloading, templates | Virtual functions (overriding) |
| Early / static binding | Late / dynamic binding via vtable |
Virtual Functions
#include <iostream>
using namespace std;
class Shape {
public:
virtual double area() = 0; // pure virtual => Shape is abstract
virtual ~Shape() {}
};
class Circle : public Shape {
double r;
public:
Circle(double r) : r(r) {}
double area() override { return 3.14 * r * r; }
};
class Square : public Shape {
double s;
public:
Square(double s) : s(s) {}
double area() override { return s * s; }
};
int main() {
Shape *shapes[] = { new Circle(2), new Square(3) };
for (Shape *s : shapes) { cout << s->area() << endl; delete s; }
}
12.56
9
Without virtualIf
area() weren't virtual, calling it through a Shape* would always run the base version. That's static binding.Track your progress through the C++ course