Polymorphism and Function-Table Dispatch
Dynamic polymorphism lets client code call a common operation while the concrete type supplies its behavior.
What is Polymorphism and Function-Table Dispatch?
Dynamic polymorphism lets client code call a common operation while the concrete type supplies its behavior.
Select behavior through a common interface.
Important points
- Understand the C mechanism before comparing the C++ abstraction.
- Use RAII and value semantics to express ownership.
- Prefer type-safe compile-time abstractions over macros and casts.
C and C++ code examples
main.c
#include <stdio.h>
typedef struct Shape Shape;
struct Shape {
double value;
double (*area)(const Shape *shape);
};
double square_area(const Shape *shape) {
return shape->value * shape->value;
}
int main(void) {
Shape square = {4.0, square_area};
printf("area=%.1f\n", square.area(&square));
}
area=16.0
C++
main.cpp
#include <iostream>
struct Shape {
virtual double area() const = 0;
virtual ~Shape() = default;
};
struct Square : Shape {
double side;
explicit Square(double value) : side(value) {}
double area() const override { return side * side; }
};
int main() {
Square square(4);
const Shape& shape = square;
std::cout << "area=" << shape.area() << '\n';
}
area=16
C and C++ comparison
C builds an explicit object pointer plus function table. C++ virtual functions generate comparable dispatch machinery and use a virtual destructor for safe base-pointer deletion.
C
C uses naming conventions, callbacks, macros, and explicit context structures.
C++
Language features provide scoped, type-safe, and often zero-overhead abstractions.
Practice exercises
Run both versions, then modify them to observe the different language guarantees.
- Write the C mechanism before the C++ abstraction.
- Remove manual cleanup with RAII.
- Check whether the abstraction adds allocations or virtual dispatch.