Skip to content

Last updated:2026-10-12

Implementing C++ Polymorphism in C

About the Author

WeChat official account:

wechat

1. A C++ Implementation Example

Polymorphism in C++: C++ maintains a virtual function table, and by the assignment compatibility rules we know that a base class pointer or reference can point to a derived class object.

If a base class pointer or reference calls a virtual function of the base class, that base class pointer looks up the function address in its own virtual function table. If the base class pointer or reference points to a derived class object, and that derived class has overridden the base class's virtual function, then the pointer calls the derived class's overridden virtual function.

See the example code at: c++_examp.cpp

2. C Implementation

  • Encapsulation

The C language has no concept of a class, but it does have structs, so we can consider using a struct to simulate one;

Use function pointers to encapsulate attributes and methods inside a struct.

  • Inheritance

Struct nesting

  • Polymorphism

The function pointers of a class and of its subclass differ

Inside a C-language struct there are no member functions, so how do we implement a function shared by the parent struct and the child struct? We can consider simulating it with function pointers. But that approach has a flaw: the parent's and the child's own function pointers point not to something like the virtual function table maintained in C++ but to a block of physical memory; if too many functions are simulated this way, it becomes hard to maintain.

To simulate polymorphism, the function pointer variables must stay aligned (identical in content and identical in variable alignment). Otherwise, a parent class pointer pointing to a child class object will crash at run time!

See the example code at: c_examp.c

Comments