Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I simulate OO-style polymorphism in C?

Is there a way to write OO-like code in the C programming language?


See also:

  • Can you write object-oriented code in C?
  • Object-orientation in C

Found by searching on "[c] oo".

like image 242
prinzdezibel Avatar asked Feb 07 '09 16:02

prinzdezibel


People also ask

Can you do OO in C?

In principle OOP can be done in any language, even assembly. This is because all OO language compilers/assemblers (e.g. C++) ultimately translate the high level constructs of the language into machine language.

How can we use C language to demonstrate polymorphism?

Polymorphism example in C++ Polymorphism is a key feature of object oriented programming that means having multiple forms. This is divided into compile time polymorphism and runtime polymorphism in C++. An example of compile time polymorphism is function overloading or operator overloading.

What does it mean when we apply polymorphism to OO design?

Polymorphism is one of the core concepts in OOP languages and describes the concept wherein you can use different classes with the same interface. Each of these classes can provide its own implementation of the interface.

Is polymorphism possible in C language?

Polymorphism as a feature of object-oriented languages is not available in C. Neither are encapsulation and inheritance - the language does not have the corresponding features.


1 Answers

The first C++ compiler ("C with classes") would actually generate C code, so that's definitely doable.

Basically, your base class is a struct; derived structs must include the base struct at the first position, so that a pointer to the "derived" struct will also be a valid pointer to the base struct.

typedef struct {    data member_x; } base;  typedef struct {    struct base;    data member_y; } derived;  void function_on_base(struct base * a); // here I can pass both pointers to derived and to base  void function_on_derived(struct derived * b); // here I must pass a pointer to the derived class 

The functions can be part of the structure as function pointers, so that a syntax like p->call(p) becomes possible, but you still have to explicitly pass a pointer to the struct to the function itself.

like image 64
UncleZeiv Avatar answered Sep 19 '22 03:09

UncleZeiv