i was told objects can be created in C just like c++. Does anyone happen to have any examples of how this is done or any recommended resources on this :) thx

7 Years
Discussion Span
Last Post by Narue

i was told objects can be created in C just like c++.

Objects are really just lumping data and functions that operate on the data into one package. In C you can't have member functions, but you can have pointers to functions:

#include <stdio.h>

typedef struct foo foo;

struct foo {
    int data;
    void (*add)(foo *self);

void foo_add(foo *self)

int main()
    foo obj = {0, foo_add};
    int i;

    for (i = 0; i < 10; i++) {
        printf("%d\n", obj.data);

    return 0;

The process is lower level than C++ in that you need to manually handle some of the things that C++ does for you, such as passing the this pointer to member functions and attaching member functions to each object on initialization.

Objects like this are easy. The complication is introduced when one wants to implement inheritance and polymorphism to C, which usually results in ridiculous abuse of the preprocessor. ;)

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.