User:Ujoimro/object oriented programming in c

Though not enforced, object oriented programming is possible in C. The main constraints added by C++ can be accepted as a convention in the source code. The object oriented programming paradigm is widely used in C projects including the Linux kernel and SQLite.

Classes
Classes are composed from two major entity types: data and methods. There is already a tool in C to create structured data types: struct. Simple classes can be translated directly in C:

class person: name height age

can be translated as

struct person { char*name; int height; int age; }

The methods can be declared as functions, whereas the pointer to the data of the class is put -- by convention -- as first parameter:

class person: name height age def set_age(self, n): self.age=n

could be translated as

struct person { char*name; int height; int age; }

void set_age(person * self, int age) { self->age=age; }

methods can also be directly included in the structures

struct person { char*name; int height; int age; void (*set_age)(struct person*, int); }

This allows virtual methods, as the method can be set during the allocation:

void set_age_v1(person * self, int age) { self->age=age+1; }

void set_age_v2(person * self, int age) { self->age=age+2; }

struct person p1; p1->set_age=&set_age_v1;

p1->set_age(p1, 10);