C programming / object patterns

Classes in C: Structs, Methods and Encapsulation

The C standard has no class among its reserved words. A struct holds the state, functions with a pointer to it as first parameter act as methods, a header with an incomplete type hides the fields, and a table of function pointers gives polymorphism.

Published
ScopeISO C patterns
Reserved word classnone
Patterns3
Layout rule for inheritance1

One Stack object from stack_new to stack_free

  1. The header shows one type name and 5 prototypes; no field is visible.

    A caller includes stack.h and finds the declaration typedef struct Stack Stack with 5 function prototypes and 0 fields. The draft N3220 treats a structure of unknown content as an incomplete type, and a pointer to such a type is allowed. So a caller can hold a Stack pointer, store it and pass it on without knowing how large the object behind it is.

  2. stack_new reserves 24 bytes, sets every field and returns the pointer.

    The call to stack_new asks malloc for sizeof *s, which measures 24 bytes here: a pointer and two counters of 8 bytes each. It sets items to NULL, size to 0 and capacity to 0, then returns the address. From this moment the variable s in main holds the identity of the object, and main is responsible for ending it.

  3. stack_push takes the pointer first; 3 pushes give size 3 and capacity 4.

    Every method receives the object's address as its first parameter, which plays the role of this. The first push finds size equal to capacity, so realloc reserves block B with room for 4 ints, 16 bytes. The pushes of 10, 20, 30 then fill it. Block A now owns block B through the items field, and main still sees only the pointer s.

  4. stack_pop delivers 30 through the out parameter, and the size shrinks to 2.

    The pop lowers size first and copies the item at the new index into the caller's variable, so the return value stays free to report an empty stack. The program prints popped 30, 2 left. Nothing is released: capacity stays 4, block B keeps its 16 bytes, and the old value remains in its slot, no longer counted as part of the stack.

  5. A caller writes s->size and Apple clang 12.0.0 refuses: incomplete definition of type 'struct Stack'.

    A second source file includes only stack.h and reaches for a field. The compiler knows the name Stack but not its members, so it stops with an error. Declaring a Stack by value fails too, with the message: variable has incomplete type. These messages come from Apple clang 12.0.0; GCC words them differently. The author can therefore change the layout without touching any caller.

  6. One call, two tables: writer_write reaches file_write or mem_write through each object's table.

    The stack needs no table, because it has one implementation. A writer has two, so each object begins with a base member holding a pointer to a const table of functions. The loop calls writer_write on both objects and never asks which kind it has. file_write sends 6 bytes to standard output, mem_write stores 6 in memory. The base member sits at offset 0 in both types.

  7. stack_free releases block B, then block A; s keeps a stale address and must stay unused.

    The ending call frees the items first, because they are reached through the object, and the object second. After it, 0 blocks and 0 bytes remain in use. The variable s has not changed: it still holds the old address, and nothing in the language marks it as stale. That it stays unused is an agreement between caller and implementer, not a rule the compiler enforces.

  8. Shown, not run: a second stack_free would touch released memory 3 times.

    Calling stack_free again on the same pointer repeats its steps on blocks that no longer belong to the program: it reads s->items from freed block A, then frees block B a second time and frees block A a second time. Double frees and use after free have undefined behavior and give no reliable error at the call. Setting s to NULL first protects that one variable: the recorded call stack_free(NULL) frees 0 blocks.

The header

The header shows one type name and 5 prototypes; no field is visible.

Source

Memory

Who owns what

    Recorded run: Apple clang 12.0.0, arm64, cc -std=c11 -Wall -Wextra -pedantic. Addresses are shown as block names. Sources: Working draft N3220 of ISO/IEC 9899:2024, cppreference, struct declaration, cppreference, pointer declaration.

    Classes in C are a convention, not a language feature. The list of reserved words in the working draft N3220 of ISO/IEC 9899:2024 (C23) contains struct, typedef, union and void, but no class. C classes are therefore assembled from parts the language does provide: a struct for state, functions for behavior, an incomplete type to hide fields and, where several implementations share one interface, a table of function pointers.

    Three patterns cover almost every case. A public struct is a plain value type. An opaque type keeps its fields behind a pointer. A type with a method table lets callers use one interface for several implementations. Each has a price: the first exposes its layout, the second needs an allocation, the third adds an indirection and a rule to follow.

    Does C have classes?

    Not as a language feature. Class declarations, access levels and member functions come with C++ and C#, and C offers none of them. What C offers is enough to build the same idea by agreement between the author of a type and the people who call it.

    The word “object” needs care. The C standard defines an object as a “region of data storage in the execution environment, the contents of which can represent values” (3.18 in the draft). An int variable is an object in that sense, and so is a struct. Whether C has objects in the object-oriented sense is a separate question, and the answer is no: nothing in the language ties an object to the functions that operate on it. That tie is made by naming and by a first parameter that carries the address.

    A struct is the natural anchor. The draft describes a structure type as a sequentially allocated, nonempty set of member objects, and it does not allow a member of function type. State lives in the struct, behavior sits next to it in functions, and the rest is discipline.

    What is a class in C programming?

    A class combines an identity, a state and a behavior. C keeps the three apart and leaves the joining to the programmer. The identity of an object is its address, the state is the set of struct members stored there, and the behavior is a family of functions that receive the address as their first parameter.

    Part of a classCounterpart in C
    IdentityThe address of the object, usually held in a pointer
    StateThe members of a struct
    BehaviorFunctions that take a pointer to the struct as first parameter
    ConstructionA function such as stack_new that sets the starting state
    CleanupA function such as stack_free that releases what construction acquired
    Hidden membersA header that declares the struct without defining it

    C++ and C# attach all of this to one declaration introduced by the word class. In C the same words describe how to lay out a header and a source file, and the compiler checks nothing beyond what types and prototypes already check.

    How do I implement a class in C with a struct and functions?

    A class in C takes five decisions, made in this order.

    1. Choose a name prefix, here stack_, so that every function of the class in C belongs visibly to one type.
    2. Define the struct that holds the state: a pointer to the items, the number in use and the capacity.
    3. Write a constructor-style function that returns a pointer to a fully initialized object, or NULL when allocation fails.
    4. Write the methods. Each takes a pointer to the object as its first parameter, which plays the role of this.
    5. Write a destructor-style function that releases everything the constructor and the methods allocated.

    The header is the whole public interface. It rests on the C struct, whose definition stays in the source file.

    #ifndef STACK_H
    #define STACK_H
    
    #include <stdbool.h>
    #include <stddef.h>
    
    typedef struct Stack Stack;
    
    Stack *stack_new(void);
    void stack_free(Stack *s);
    bool stack_push(Stack *s, int value);
    bool stack_pop(Stack *s, int *out);
    size_t stack_size(const Stack *s);
    
    #endif
    #include <stdlib.h>
    #include "stack.h"
    
    struct Stack {
        int *items;
        size_t size;
        size_t capacity;
    };
    
    Stack *stack_new(void) {
        Stack *s = malloc(sizeof *s);
        if (s == NULL) return NULL;
        s->items = NULL;
        s->size = 0;
        s->capacity = 0;
        return s;
    }
    
    void stack_free(Stack *s) {
        if (s == NULL) return;
        free(s->items);
        free(s);
    }
    
    bool stack_push(Stack *s, int value) {
        if (s->size == s->capacity) {
            size_t cap = s->capacity ? s->capacity * 2 : 4;
            int *p = realloc(s->items, cap * sizeof *p);
            if (p == NULL) return false;
            s->items = p;
            s->capacity = cap;
        }
        s->items[s->size++] = value;
        return true;
    }
    
    bool stack_pop(Stack *s, int *out) {
        if (s->size == 0) return false;
        *out = s->items[--s->size];
        return true;
    }
    
    size_t stack_size(const Stack *s) {
        return s->size;
    }

    A short program uses the class through the prototypes alone:

    #include <stdio.h>
    #include "stack.h"
    
    int main(void) {
        Stack *s = stack_new();
        if (s == NULL) return 1;
        stack_push(s, 10);
        stack_push(s, 20);
        stack_push(s, 30);
    
        int top;
        if (stack_pop(s, &top)) {
            printf("popped %d, %zu left\n", top, stack_size(s));
        }
        stack_free(s);
        return 0;
    }

    Compiled with cc -std=c11 -Wall -Wextra -pedantic on Apple clang 12.0.0, the program builds without a diagnostic and prints popped 30, 2 left.

    Two details deserve a look. The constructor returns NULL when malloc fails, and the caller checks for it before use. The pop method reports an empty stack through its return value and delivers the item through an out parameter, because a plain int result could not tell an empty stack from a stored zero.

    What types of classes can I build in C?

    The three patterns differ in what callers may see and what the author may change later.

    PatternCallers can seeTypical use
    Public structEvery member; instances can live on the stackSmall value types whose layout is part of the contract, such as a point or a range
    Opaque typeA pointer and the function prototypesAbstract data types such as the stack above; the layout can change freely
    Method tableA base struct holding a pointer to a table of functionsOne interface with several implementations, such as output streams

    A public struct fits when the representation is part of the contract. Callers can allocate it on the stack and read fields directly, but they also take over its invariants. If an update must obey a rule, route it through a function even when the fields are visible, because a direct write bypasses validation.

    The opaque type is the default for anything with an internal invariant or a layout likely to change. The method table is the heaviest pattern and belongs where a caller works with several implementations through one interface. Where behavior needs no remembered state at all, plain functions without any struct are simpler still, which is the territory of functional programming.

    How do I hide private fields with an opaque type?

    The header declares the type without defining it: typedef struct Stack Stack;. A structure type of unknown content is an incomplete type in the C draft, and the definition in one source file completes it there. Pointers to an incomplete type are allowed everywhere, so callers can pass a Stack * around, store it and hand it back to the functions of the class. Callers that need to read a value get an accessor such as stack_size, which returns a copy instead of exposing the field, so the representation stays private while the interface stays complete.

    Looking inside is what they cannot do. Member access and the creation of an object on the stack both fail, because the size is unknown to every file except the one with the definition. This translation unit reaches for a field:

    #include "stack.h"
    
    size_t peek_size(Stack *s) {
        return s->size;
    }

    Apple clang 12.0.0 rejects it; GCC and newer clang versions word the message differently:

    peek.c:4:13: error: incomplete definition of type 'struct Stack'
        return s->size;
               ~^

    Declaring Stack s; fails the same way, with “variable has incomplete type”. The payoff is freedom. The author can add a field, reorder the members or replace an array with a linked list without changing the source of a single caller, because no caller depends on the layout. The price is that every object comes from a constructor, usually through malloc, and every access costs a function call.

    How do I add methods and polymorphism in C?

    Plain prefixed functions are enough while a type has one implementation. When different implementations must satisfy one interface, a table of function pointers moves the choice to run time. Pointers to functions exist for callbacks of this kind, and a struct may hold a member of type “pointer to function” even though it may not hold a member of function type.

    Function pointers are not required for a class in C. A plain function that takes a struct pointer is simpler, and the stack above has no table at all. The table pays for itself only when callers must choose an implementation at run time through one interface.

    The example defines a writer interface with two implementations, one that writes to a stream and one that fills a small memory buffer. Each concrete type starts with a Writer member, and that member holds the pointer to the table.

    #include <stdio.h>
    #include <string.h>
    #include <stddef.h>
    
    typedef struct Writer Writer;
    
    typedef struct {
        size_t (*write)(Writer *self, const char *data, size_t size);
    } WriterOps;
    
    struct Writer {
        const WriterOps *ops;
    };
    
    static size_t writer_write(Writer *w, const char *data, size_t size) {
        return w->ops->write(w, data, size);
    }
    
    typedef struct {
        Writer base;
        FILE *out;
    } FileWriter;
    
    typedef struct {
        Writer base;
        char buf[32];
        size_t len;
    } MemWriter;
    
    static size_t file_write(Writer *w, const char *data, size_t size) {
        FileWriter *f = (FileWriter *)w;
        return fwrite(data, 1, size, f->out);
    }
    
    static size_t mem_write(Writer *w, const char *data, size_t size) {
        MemWriter *m = (MemWriter *)w;
        size_t room = sizeof m->buf - m->len;
        if (size > room) size = room;
        memcpy(m->buf + m->len, data, size);
        m->len += size;
        return size;
    }
    
    static const WriterOps file_ops = { file_write };
    static const WriterOps mem_ops = { mem_write };
    
    int main(void) {
        FileWriter f = { { &file_ops }, stdout };
        MemWriter m = { { &mem_ops }, {0}, 0 };
        Writer *all[] = { &f.base, &m.base };
    
        for (size_t i = 0; i < 2; i++) {
            writer_write(all[i], "hello\n", 6);
        }
        printf("memory holds %zu bytes\n", m.len);
        printf("offset of base: %zu, %zu\n", offsetof(FileWriter, base), offsetof(MemWriter, base));
        printf("same address: %d\n", (void *)&m == (void *)&m.base);
        return 0;
    }

    The program writes hello once to standard output, then reports that the memory writer holds six bytes. The loop in main never asks which kind of writer it has.

    Keep the table const and complete. Every constructor has to install a table with all entries filled, since calling a null function pointer is undefined behavior. Copying a polymorphic object by value is risky for a related reason: the copy shares the table, but not necessarily the resources the original owns. Unless the interface defines copy behavior, pass pointers and let one owner decide when the object ends.

    How do I manage ownership and lifecycle of C objects?

    A C object has no destructor that runs on its own, so its lifetime is an agreement between caller and implementer. Writing the agreement into the header and into the function names prevents most defects. Five questions need an answer for every type.

    1. Which function creates an object and which one ends it? Pair them by name: stack_new with stack_free, or _init with _deinit when the caller supplies the storage.
    2. Who calls the ending function? Exactly one owner, named in the documentation.
    3. Does the ending function accept NULL? The stack above does and returns at once, so cleanup paths need no special case.
    4. Does a function borrow a pointer or take ownership of it? A function that stores its argument must say so.
    5. How long does a returned pointer stay valid? State whether a later push or pop invalidates it.
    PatternAllocationCleanup
    Public value structCaller stack or containing struct_deinit if resources exist
    Opaque object_new or _create_free or _destroy
    Caller-provided storageCaller bufferExplicit _deinit

    Two defects dominate. Freeing an object twice and using it after it was freed both have undefined behavior, and neither gives a reliable error at the point of the call. Setting the pointer to NULL after the ending call turns a later misuse of that variable into an obvious null access, but it protects only that one copy of the pointer. A test that creates, uses and frees every object under a memory checker is worth keeping next to each class.

    Object-oriented C can be robust when ownership, nullability and lifecycle rules are explicit and the interfaces stay small. The compiler cannot enforce all of those rules, which is why the checks and tests carry so much weight.

    How is inheritance done in C?

    C has no inheritance, but a layout rule imitates it. A struct that must act as a subtype places the base struct as its first member. The draft guarantees that member addresses increase in declaration order, that a suitably converted pointer to a structure points to its first member and the reverse, and that a structure has no padding at its beginning (6.7.3.2 of N3220). A pointer to the derived object can therefore serve as a pointer to the base. Going up needs no cast, only the address of the base member, as in &f.base; going back down needs one. In the writer example the cast inside file_write relies on exactly this, and two lines of main confirm it:

    printf("offset of base: %zu, %zu\n", offsetof(FileWriter, base), offsetof(MemWriter, base));
    printf("same address: %d\n", (void *)&m == (void *)&m.base);
    offset of base: 0, 0
    same address: 1

    The convention stops there. No base constructor runs by itself, so each derived constructor must set the base member. Nothing enforces access rules. A cast from a base pointer to a derived pointer is correct only if the object really has the derived type, and the compiler cannot check that; a type tag, or a comparison of the table pointer with a known table, can serve as a manual check.

    Composition is often simpler. The new struct holds a component as an ordinary member and forwards the operations it wants to expose. It needs no cast, and nothing breaks when the layout of the component changes. Simulated inheritance earns its place where substitutability is a real requirement, as with the writers above, and not merely to reproduce a class hierarchy from another language.

    How do C classes compare with C++ classes?

    C++ builds classes into the language. Most of what C does by convention is a declaration there, checked by the compiler.

    AspectCC++
    Class syntaxNone; a struct plus functions by conventionThe class construct
    StructData members only, no member functionsIdentical to a class except for the default access and the default inheritance
    Scope of a structNot a scopeA scope
    Hiding membersOpaque types and file-local definitionsAccess levels declared in the class
    DispatchA table of function pointers built by handVirtual functions that derived classes can override

    The mechanisms are alike in spirit. The difference is who keeps the books: C++ does it in the compiler, C leaves it to the author. For the code that is valid C and rejected by a C++ compiler, the guide to C vs C++ goes through the cases one by one.

    FAQ

    Frequently asked questions

    01Can a C program be organized into classes without switching to C++?

    Yes. A struct for the state, functions that take a pointer to it and a header that hides the fields give the same structure. The compiler enforces only what types and prototypes already enforce, so the rest depends on the discipline of the people writing the code.

    02What is a class in coding?

    A class describes a kind of object: the data every instance holds and the operations available on it. C++ and C# have a syntax for it. C expresses the same idea through a convention of structs and functions.

    03What are types of classes?

    The answer depends on the language, and C has no class construct to classify. In practice three C patterns stand in for the idea: a public struct, an opaque type and a type with a method table, each with a different degree of hiding.

    04What is inheritance and what are its types?

    Inheritance lets a derived type reuse the data and operations of a base type. Languages differ in what they allow, for instance a single base or several. C has only a layout convention that places the base struct first, and it adds no rules beyond that.

    05Which is harder, C++ or C?

    The sources used here give no scale, so this is an editorial judgment. C has fewer language features to learn but leaves memory and conventions entirely to the programmer. C++ has many more features, and a beginner has to learn more of them before writing larger programs.

    06Does C have objects?

    In the sense of the C standard, yes: any region of storage that can hold values is an object. In the object-oriented sense, no, because nothing in the language binds an object to the functions that work on it. That link is a naming and parameter convention.