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 class has an equivalent C structure with all data members defined in the class. The structure can be obtained by removing all functions from the class and keeping the data member defined in the same order.
  • There is a C like function for each class function. The name of the function is generated as per name mangling described in the previous chapter. But in this example, the mangled name is not used for readability.
  • There is only one function definition of the C like function described above. The code of the function is not duplicated for each object.
  • The equivalent C function has an extra argument. This is a pointer to the object on which the method is called.
  • The static function does not have the extra argument. The static function does not require any object to be invoked.

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.

 



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

© 2012 avabodh.com — All rights reserved.