TemplatesTopTranslating Java classes into C++

Translating Java classes into C++

Recall that last time we looked at the code for stacks and nodes.

So far, we have avoided discussing what the text refers to as the "big three": destructors, copy constructors, and operator=. Let's start with destructors.

Until the stack class, all of our classes had no code for the class destructor (which is always written tilde C, if C is the name of the class.) When an object goes is popped off of the stack or is explicitly "deleted", destructors are automatically called on all of its instance variables. Usually this is sufficient, e.g., for nodes, but sometimes more is needed, as with stack. Because the stack is held as a linked list, one of its instance variables is a pointer to a node, which points to another node, etc. Because the default destructor on a pointer, just recycles that object, we need to be more explicit in the code. In particular, we must go through the entire stack and pop off all of the elements. Notice that pop does call delete on the pointers to nodes that are being deleted. This returns those nodes to the stack of avaliable space.

Copy constructors are called whenever an assignment is made from an expression to a variable or when a parameter is passed by value. If a pointer or primitive data type is being assigned, then it is simply copied. However, if the data structure is more complicated (like a linked list implementation of a stack), then more work must be done.

Finally we have to override the assignment operator so that it makes a deep copy when an assignment is made to an object on the stack. Note that once we have the assignment statement, we can easily write the copy constructor - see the sample code.

Note that the following:

    stack copy = original;
    stack copy(original);

both invoke the copy constructor. Whereas other assignments, where both objects already exist, use "=".

The idea is that writing

    copy = original;

results in the execution of

    copy.operator=(original);

where operator= has the following prototype in class C:

    C & C::operator=(const C & orig);

Notice that assignment can be chained in C++. That is, a = b = c; will be interpreted as

    a.operator= (b.operator= (c));

This is why the result of "=" is an object.


TemplatesTopTranslating Java classes into C++