Class and Structure


C++ class translation

Let's start with a simple example.
class myClass
{
public:
    int memberVar;
    int getVal(int val2) { return memberVar + val2;}
};
usage of the class:
myClass mycs;
int x = mycs.getVal(2);
The equivalent C code:
struct myClass
{
    int memberVar;
};
int myClass_getVal(myClass *this, int val2)
{
    return this->memberVar + val2;
}
And the usage:
myClass mycs;
int x = myClass_getVal(&mycs, 2);

If you take the above C++ code and compile it by g++ compiler, then the g++ will generate the corresponding equivalent C code. The C++ compiler may not go through the route of generating a C code from the C++ code and then generating assembly language code from the C code. All the modern C++ compilers directly generate assembly from the C++ code. In the above example (and examples in other chapters) the equivalent C code can be understood as C code which will generate the same assembly as the corresponding C++ code.

Here are few points to understand this:

The example shows the usage of a public variable. Most of the time there is no difference in the code generation of public, protected or private members. The compiler may use different strategies for optimization based on the access modifiers. For example it may remove the private unused member.

 


up

Want to learn (C/C++ internals) directly from the author using video call? Learn more

Do you collaborate using whiteboard? Please try Lekh Board - An Intelligent Collaborate Whiteboard App