Implementing OOP in C vs OOP in C++


In C++ you can have methods/class functions but in C that is not possible. However it is common for some people to use a constructor function in C and then assign function addresses to function pointers within the struct. For example:

#include <stdio.h>

void func_wave()

void func_handshake()

typedef struct {

    void (*wave)();
    void (*handshake)();


Greet initGreet()
    Greet var = {.wave = func_wave, .handshake = func_handshake};
    return var;

int main()
    Greet greet_instance = initGreet();

    return 0;

To me this is similar to C++ OOP except it requires some extra work.

My question is: Is this slower than using methods/member functions?

>Solution :

Is this slower than using methods/member functions?

Depends on your use case. You’re wasting space for function pointer storage but generally its slow.

How much space do function pointers take?

It depends on the machine word size. Use sizeof() operator to find for your machine.

For example is it like int pointers where they have a set size to store the address?

Please see this answer.

If it does work like that does that mean that the size of function pointers are all the same or does it depend on the return type of a function?

Size of function pointers are same but may not be equal to void * as per standard. Function pointer’s type depends on the return type not its size.

Leave a ReplyCancel reply