Constructor and Destructor


 


Lets take the example of this class:
class myClass
{
public:
    myClass() { memberVar = 0; }
    int memberVar;
    int getVal(int val2) { return memberVar + val2;}
};
myClass mycs;
int x = myClass.getVal(2);

The equivalent C code will be:
struct myClass
{
    int memberVar;
};
void myClass_ctor(myClass *this)
{
  this->memberVar = 0;
}
int myClass_getVal(myClass *this, int val2)
{
    return this->memberVar + val2;
}

The code for constructor is generated same as other methods. The code for calling constructor will be generated at the code where the object is instantiated.

The usage (of the class) code will be translated as:
struct myClass mycs;
myClass_ctor(&mycs);
int x = myClass_getVal(&mycs, 2);

Compared to the previous code, here is one extra call after the object declaration. This is generated by the compiler and is transparent to the user. Whenever object is created, the compiler generate the invocation call to constructor method on the object.

If the object is created using new operator as

myClass *mycs = new myClass;
int x = mycs->getVar(2);

The equivalent C code will be
struct myClass *mycs = (struct myClass *)operator_new(sizeof(myClass));
myClass_ctor(mycs);
int x = mycs->getVar(mycs, 2);


The operator_new(unsigned) is similar to C malloc() function. The new operator can be overridden by programmer.

Destructor translation

There is similar code generated for the destructor. The invocation to destructor is generated when the object is deleted or goes out of scope. We will discuss in detail of how compiler generate the code for object going out of scope in a different chapter.


up