Coding

Classes in C: Structs and Function Pointers Explained

C has no classes. To get the same effect, define a struct for the data, write functions that take a pointer to that struct as their first argument, and add function pointers to the struct when you need methods that can be swapped at run time.

#include <stdio.h>

struct counter {
    int value;
};

void counter_init(struct counter *self)
{
    self->value = 0;
}

void counter_increment(struct counter *self)
{
    self->value++;
}

int main(void)
{
    struct counter c;
    counter_init(&c);
    counter_increment(&c);
    counter_increment(&c);
    printf("%d\n", c.value);
    return 0;
}

Example output:

2

What C has instead of classes

A class in C++ or Java bundles three things: data, the functions that work on the data, and rules about who may touch what. C gives you the first as a struct and leaves the other two to convention. A struct is a user-defined type that groups named members, and the members are stored in the order you declare them. The functions live outside the struct, and nothing in the language ties them to it.

The convention that makes this feel like a class is simple. Pick a prefix for the type, name every related function with that prefix, and pass a pointer to the struct as the first parameter. In the example above, counter_init plays the role of a constructor and counter_increment plays the role of a method. The parameter is called self here, but the name is only a habit borrowed from other languages. C does not require it.

If structs are new to you, struct in C covers declaration, initialization and the . and -> operators in detail. The rest of this article assumes you know them.

Why the first argument is a pointer

C passes arguments by value. If counter_increment took a struct counter instead of a pointer, it would modify a copy and the caller's counter would never change. Passing the address lets the function change the original through self->value. For read-only functions, use const, as in int counter_get(const struct counter *self). The compiler then rejects any write through self, which is the nearest C comes to a const method. For a refresher on addresses and dereferencing, see pointers in C explained.

Constructors and destructors: create and destroy functions

C will not run code when an object is created or goes out of scope. You write that code as ordinary functions and call them yourself. A common pair allocates the object on the heap and returns a pointer, then releases it:

#include <stdlib.h>

struct stack {
    int *items;
    size_t count;
    size_t capacity;
};

struct stack *stack_create(size_t capacity)
{
    struct stack *self = malloc(sizeof *self);
    if (self == NULL) {
        return NULL;
    }
    self->items = malloc(capacity * sizeof *self->items);
    if (self->items == NULL) {
        free(self);
        return NULL;
    }
    self->count = 0;
    self->capacity = capacity;
    return self;
}

void stack_destroy(struct stack *self)
{
    if (self == NULL) {
        return;
    }
    free(self->items);
    free(self);
}

Two details matter. First, the create function checks every allocation and cleans up the first one if the second fails, so a failure leaves nothing leaked. Second, the destroy function accepts NULL and does nothing, which mirrors how free(NULL) behaves and makes cleanup code simpler. The language will never call stack_destroy for you, so every path that creates a stack must eventually reach it. The details of allocation failure and leaks are in malloc in C.

Private members with an opaque type

C has no private keyword. Every member of a struct is readable and writable by any code that can see the definition. To hide the members, split the type across a header and a source file.

In stack.h, declare the tag without defining it. Per cppreference, until the definition appears the struct name has incomplete type, and you can still declare pointers to it:

/* stack.h */
struct stack;                                  /* incomplete type */

struct stack *stack_create(size_t capacity);
void stack_destroy(struct stack *self);
int stack_push(struct stack *self, int value);

In stack.c, give the full definition. Code that includes only the header can store and pass a struct stack *, but any attempt to write s->count or sizeof(struct stack) fails to compile because the type is incomplete there. This is as close to encapsulation as C gets. The trade-off is that callers cannot create a stack on their own stack frame, since they do not know its size, so they must use your create function.

Methods through function pointers

A struct cannot contain a function. Members of function type are not allowed. It can contain a pointer to a function, because a pointer type is always complete. The declaration syntax puts the name in parentheses with the star:

int (*fp)(int);    /* fp is a pointer to a function taking int, returning int */

You can assign a function to it with or without the address-of operator, since the function name converts to a pointer automatically, and you call it like a function. Both fp(7) and (*fp)(7) work. Unlike functions, function pointers are objects, so they can be stored in structs and arrays, copied and passed as arguments.

Put those pointers in a struct and you have a per-object method:

#include <stdio.h>

struct button {
    const char *label;
    void (*on_click)(const struct button *self);
};

static void say_hello(const struct button *self)
{
    printf("%s clicked\n", self->label);
}

int main(void)
{
    struct button ok = { .label = "OK", .on_click = say_hello };
    ok.on_click(&ok);
    return 0;
}

Example output:

OK clicked

Note that you pass &ok yourself. C has no implicit this, so the object must be handed to its own method explicitly. This pattern is how callbacks work in many C libraries: the caller supplies a function, and the library calls it later.

Polymorphism with a table of function pointers

Storing a pointer per object works, but it wastes space when many objects share the same behavior. The usual fix is a table of function pointers, often called a vtable, which every object of one kind points to. Inheritance is imitated by placing a base struct as the first member of each derived struct:

#include <stdio.h>

struct shape;

struct shape_ops {
    double (*area)(const struct shape *self);
};

struct shape {
    const struct shape_ops *ops;
};

struct circle {
    struct shape base;      /* must be first */
    double radius;
};

struct rectangle {
    struct shape base;      /* must be first */
    double width;
    double height;
};

static double circle_area(const struct shape *self)
{
    const struct circle *c = (const struct circle *)self;
    return 3.14159265358979 * c->radius * c->radius;
}

static double rectangle_area(const struct shape *self)
{
    const struct rectangle *r = (const struct rectangle *)self;
    return r->width * r->height;
}

static const struct shape_ops circle_ops = { circle_area };
static const struct shape_ops rectangle_ops = { rectangle_area };

int main(void)
{
    struct circle c = { { &circle_ops }, 2.0 };
    struct rectangle r = { { &rectangle_ops }, 3.0, 4.0 };
    const struct shape *shapes[] = { &c.base, &r.base };

    for (int i = 0; i < 2; i++) {
        printf("%.2f\n", shapes[i]->ops->area(shapes[i]));
    }
    return 0;
}

Example output:

12.57
12.00

The loop treats both objects as plain struct shape and still gets the right area for each, which is what a virtual method does in C++. The cast inside circle_area is safe only because base is the first member. The C standard allows no padding before the first member of a struct, and a pointer to a struct can be converted to a pointer to its first member and back. If you reorder the members, the cast silently reads the wrong memory, so keep the comment next to base and never move it.

Limits of this approach

Everything above is discipline, not language support. The compiler will not stop you from calling circle_area on a rectangle if you cast the pointer by hand, and it will not warn you when you forget to call stack_destroy. Each new class needs its own operations table and its own create and destroy functions, so the boilerplate grows quickly. There is no overloading, no templates and no automatic cleanup.

Because of that, keep the technique small. A single struct with a handful of functions is clear and idiomatic C. A deep hierarchy built from tables of function pointers is hard to read and easy to break, and at that point a language with real classes is usually the better tool. The comparison article Python vs C shows how much C leaves to the programmer in general.

Common mistakes

  • Calling a function pointer that was never set. A struct member you did not initialize holds an indeterminate value if the struct is a local variable. Start with = { 0 } or designated initializers, and check for NULL before calling optional callbacks.
  • Passing the struct by value to a mutating function. The function changes a copy. Pass a pointer.
  • Forgetting the matching destroy call. If a create function allocates, document who frees, and free exactly once.
  • Not putting the base struct first. The cast from a base pointer to a derived pointer is only valid when the base is the first member.
  • Writing the function pointer declarator wrongly. int *fp(int) declares a function returning int *. You need the parentheses: int (*fp)(int).

Frequently asked questions

Does C have classes?
No. C has no class keyword, no member functions, no constructors and no inheritance. It has structs, which group data, and functions that you write separately. Programmers combine a struct with functions that take a pointer to it to get the same organization a class gives in C++ or Java.
Can a struct in C contain a function?
No. Members of function type are not allowed in a struct. A struct can contain a pointer to a function, though, and calling through that pointer gives you something that looks like a method call.
How do you make private members in C?
C has no access control on struct members. The usual technique is an opaque type: declare struct name; in the header, keep the definition in the .c file, and expose only functions that take a pointer. Code that includes the header can hold the pointer but cannot read the members.
Is there inheritance in C?
Not as a language feature. You can imitate it by placing a base struct as the first member of a derived struct. A pointer to the derived struct can then be converted to a pointer to the base, which is how a shared set of function pointers is reused across types.
Should I use C++ instead of faking classes in C?
If you want classes, virtual functions and constructors with compiler checking, C++ provides them directly. Faking classes in C makes sense when the project must stay in C, for example for an embedded target, a C-only toolchain or an existing C codebase.

Sources