Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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()
{
    printf("Wave\n");
}

void func_handshake()
{
    printf("Handshake\n");
}


typedef struct {

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

}Greet;


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


int main()
{
    Greet greet_instance = initGreet();
    greet_instance.wave();
    greet_instance.handshake();

    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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading