How would one write object-oriented code in C?

C is not an object-oriented language, but it is still possible to write code in an object-oriented style using structs and function pointers.

Here is an example of how to define a simple object in C using structs and function pointers:

c
#include <stdio.h>
#include <stdlib.h>

// Define the "class"
typedef struct {
int value;
void (*print)(void*);
} MyClass;

// Define the "constructor"
MyClass* MyClass_new(int value) {
MyClass* obj = malloc(sizeof(MyClass));
obj->value = value;
obj->print = MyClass_print;
return obj;
}

// Define a "method"
void MyClass_print(void* self) {
MyClass* obj = (MyClass*) self;
printf("Value: %d\n", obj->value);
}

// Define the "destructor"
void MyClass_free(MyClass* obj) {
free(obj);
}

int main() {
// Create a new object
MyClass* obj = MyClass_new(42);

// Call a method
obj->print(obj);

// Destroy the object
MyClass_free(obj);

return 0;
}

In this example, we define a struct called MyClass that contains a data member value and a function pointer print. We then define a “constructor” function called MyClass_new that allocates memory for the object, initializes its data members, and sets the function pointer to point to a “method” function called MyClass_print. We also define a “destructor” function called MyClass_free that frees the memory allocated by the constructor.

To call a method on an object, we simply call the function pointer with the object as its argument, as shown in the main function.

Note that this is a simplified example and does not cover all aspects of object-oriented programming, such as inheritance and polymorphism.