Skip to content

AhmedMostafa99a/Simulating-Polymorphism

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

4 Commits
 
 
 
 
 
 

Repository files navigation

Simulated Polymorphism in C++ (No Virtual Keyword)

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.

📌 Project Overview

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 virtual keyword.
  • No C++ inheritance (e.g., class Circle : public Shape).
  • No STL libraries (std::string, std::vector, etc.).

⚙️ How It Works (The Mechanics)

1. Simulated Inheritance via Aggregation

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.

2. Virtual Tables (VTables)

Dynamic function binding is simulated using a VTable struct filled with function pointers.

struct ShapeVtable {
    double (*GetArea)(Shape *);
    void (*PrintInfo)(Shape *);
};

3. Dynamic Dispatch

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.

About

Simulating C++ polymorphism and dynamic dispatch using pure C-style structs and virtual tables (vtables) without the virtual keyword.

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages