Class and Structure


C++ class translation

Lets 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 thought the route of generating a C code from the C++ code and then generate 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 same assembly as the corresponding C++ code.

Here are few points to understand this:

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

 


up