Hello All!

I was just wondering if C++ classes could internally be represented in the following way:

#include <stdio.h>

struct A {
    int a;
    void (*ptr) (A *);
};

void display(A *ptr)
{
    ptr->a = 2;
    printf("ptr->a = %d", ptr->a);
}

int main()
{
    A obj;
    obj.ptr = display;

    obj.ptr(&obj);

    return 0;
}

The C++ equivalent could be something like:

#include <stdio.h>

class A {
public:
    int a;
    void display();
};

void A::display()
{
    this->a = 2;
    printf("a = %d", this->a);
}

int main()
{
    A obj;
    obj.display();

    return 0;
}

So, do C++ compilers could actually convert C++ code to valid C code(something like the above example)? Or how exactly is it done(if done in any other way). This was just a simple class example. I couldn't think how access specifiers could be implemented in C. Any inputs would be helpful. I was just curious if the compilers actually did it this way.

Thanks a lot!

You pretty much nailed it for a simple class. It gets quite a bit more complex when construction, destruction, inheritance, polymorphism, and especially multiple inheritance enter the picture.

A good book covering the topic is this one.

@deceptikon:
Wow, that was quick :)

Thanks a lot for the link.

This question has already been answered. Start a new discussion instead.