This repository contains a C++ implementation that simulates Object-Oriented inheritance and dynamic polymorphism using pure C-style mechanics. It demonstrates how dynamic dispatch works under the hood without relying on native C++ OOP features like the virtual keyword or standard class inheritance.
In standard C++, polymorphism is achieved using classes, inheritance, and virtual functions. However, compilers actually implement this behind the scenes using Virtual Tables (vtables).
This project manually recreates that compiler behavior to calculate the areas of various geometric shapes (Circle, Rectangle, Ellipse, Square).
Constraints Followed in this Implementation:
- No
virtualkeyword. - No C++ inheritance (e.g.,
class Circle : public Shape). - No STL libraries (
std::string,std::vector, etc.).
Instead of inheriting from a base class, derived shapes "aggregate" the base Shape struct by placing it as their very first member in memory.
struct Shape { ShapeVtable *vtable; };
struct Circle {
Shape parent; // Must be the first member!
double radius;
};Because parent is the first member, a pointer to a Circle object points to the exact same memory address as the Shape object inside it. This makes safely "upcasting" ((Shape*)&circle) possible.
Dynamic function binding is simulated using a VTable struct filled with function pointers.
struct ShapeVtable {
double (*GetArea)(Shape *);
void (*PrintInfo)(Shape *);
};Each specific shape defines its own standalone functions. A global instance of the VTable is created for each shape, and the function pointers are explicitly cast to match the generic Shape* signature expected by the base VTable.
When GetArea(shape) is called in the main loop, the program dynamically looks up the specific function pointer stored in that object's initialized VTable and executes it, effectively mimicking runtime polymorphism.