Constructor and Destructor


 


Let's take an 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 the constructor is generated the same as other methods. The code for calling the 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 an object is created, the compiler generates the invocation call to the 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 the C malloc() function. The new operator can be overridden by the programmer.

Destructor translation

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


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