Object Oriented Programming in C
C is not really an object oriented language, however it is still possible to exploit some tricks in order to use common OOP techniques.
The C equivalent of a class
If you want to group variables like you would in a class in C, use struct
structures. They are similar to classes except you cannot have access qualifiers
like private
and public
, and you cannot have fancy things like functions
and subclasses (see below). Using these to make things more organized is highly
recommended.
Subclassing
You may use this common trick to implement subclassing:
typedef struct Superclass
{
int a;
int b;
} Superclass;
typedef struct SubclassOfSuperclass
{
Superclass super;
int c;
} SubclassOfSuperclass;
int SuperclassGetA (Superclass *s)
{
return s->a;
}
int SubclassDoThings (SubclassOfSuperclass *sub)
{
int foo = SuperclassGetA (&sub->super);
return foo * 2 * sub->c;
}
Imagine Superclass
and SuperclassGetA
being defined somewhere, and the
latter is something complicated you want to reuse. Here, we create a new
struct with the Superclass
inside it. Since it is the first item, a pointer
to SubclassOfSuperclass
would actually have the same value as &sub->super
.
Function pointers and virtual functions
In other languages, functionality of a class could be modified transparently by the use of a virtual function or overriding. You can do this in C by using function pointers inside the structures and setting them appropriately.