Object-Oriented C
Object-oriented C is a set of conventions: structs as data, functions as methods, opacity as encapsulation, embedding as inheritance, and vtables as virtual dispatch. The language does not enforce any of it.
Detailed Explanation
C will compile a pile of globals and a 400-line main. It will also compile a program that looks like a small C++ subset without constructors. The second style is a pattern, not a feature.
The pieces, in the order you actually adopt them:
- Group state in a struct. Prefix the functions (
widget_init). Passstruct Widget *. - Pair init and cleanup. Check failures. Do not leak on the error path.
- Hide the struct if callers should not depend on the layout (opaque type).
- Swap behavior with a function pointer or a vtable when you have more than one implementation.
- Embed a base struct at offset zero only when you truly need a base pointer.
You stop before you rebuild C++. Multiple inheritance, exceptions, and template containers are possible in C and are usually a mistake. A handful of macros to generate typed vectors is as far as most codebases should go.
Why do this at all? Because the problems — ownership, invariants, more than one instance — show up whether you name them objects or not. The pattern gives reviewers a place to look (widget_*) and gives the debugger a type to print.
The standard library already does it. FILE * is an opaque object. fopen / fread / fclose are its methods. Your types will be easier to teach if they feel like that.
This glossary's oop category is the same material taught as language idioms. This page is the design-pattern umbrella that points at those idioms.
Code Examples
#include <stdio.h>
#include <stdlib.h>
typedef struct Counter Counter;
struct Counter {
int value;
};
static Counter *counter_new(int start)
{
Counter *c = malloc(sizeof *c);
if (c == NULL) {
return NULL;
}
c->value = start;
return c;
}
static void counter_bump(Counter *c)
{
c->value++;
}
static void counter_free(Counter *c)
{
free(c);
}
int main(void)
{
Counter *c = counter_new(41);
if (c == NULL) {
return 1;
}
counter_bump(c);
printf("%d\n", c->value); /* prints: 42 */
counter_free(c);
return 0;
}Common Gotchas
None of this is checked by the compiler the way a `class` is
a stray `c->value = -1` still compiles if the struct is visible.
A vtable plus embedding plus macros is a private language
new contributors have to learn yours. Keep the subset small.
"OOP in C" is not a reason to avoid a plain function on a plain array
use the lightest tool.
Forgetting cleanup is still a leak
objects do not have destructors that run at `}`.