Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C as an object oriented language

Tags:

c

Could you suggest a syntax for the C language to use it in a similar way than an object-oriented language? I know that they cannot be the same and that some keywords aren't present in C, but I'm wondering if there is a way to take advantage of certain aspects (like inheritance) even in a C program.

like image 534
Maurizio Reginelli Avatar asked Feb 28 '10 19:02

Maurizio Reginelli


People also ask

Why is C not an OOP language?

Anything else (OOP, functional progr... C is not an object oriented programming languages because that was not the intent of its designers. C was designed to be an imperative procedural language, because that is simplest from of structured programming.

Is C is pure object oriented language?

No, it is not a purely object oriented language.


1 Answers

You can implement polymorphism with regular functions and virtual tables (vtables). Here's a pretty neat system that I invented (based on C++) for a programming exercise: alt text
(source: goblin.tkk.fi)

The constructors allocate memory and then call the class' init function where the memory is initialized. Each init function should also contain a static vtable struct that contains the virtual function pointers (NULL for pure virtual). Derived class init functions call the superclass init function before doing anything else.

A very nice API can be created by implementing the virtual function wrappers (not to be confused with the functions pointed to by the vtables) as follows (add static inline in front of it, if you do this in the header):

int playerGuess(Player* this) { return this->vtable->guess(this); }

Single inheritance can be done by abusing the binary layout of a struct: alt text
(source: goblin.tkk.fi)

Notice that multiple inheritance is messier as then you often need to adjust the pointer value when casting between types of the hierarchy.

Other type-specific data can be added to the virtual tables as well. Examples include runtime type info (e.g. type name as a string), linking to superclass vtable and the destructor chain. You probably want virtual destructors where derived class destructor demotes the object to its super class and then recursively calls the destructor of that and so on, until the base class destructor is reached and that finally frees the struct.

like image 178
Tronic Avatar answered Oct 15 '22 23:10

Tronic