CS115 Lab: C++ Constructors and Destructors

Highlights of this lab:

In this lab,  you will:

Lab Exercise:


Constructors

Copy Constructors

A copy constructor creates a clone of an existing object by initializing a new object, with an existing object of the same class. Suppose you had a class called Tree and had defined a Tree object called Pine1 To create a clone, you could enter: Tree Pine2(Pine1); or: Tree Pine2 = Pine1; If you had no copy constructor defined, then the compiler would supply a default "copy constructor" to create the clone.
Note: The first notation "Tree Pine2(Pine1);", is the current preferred syntax. The second notation "Tree Pine2 = Pine1;", is now considered obsolete. However both forms are given here because a programmer is likely to encounter both.

Copying an object using the default copy constructor may work for simple objects. However, if there were pointers in the original object, only the pointers would be duplicated, not the data that was being pointed to. Following the previous example, suppose Tree objects had an integer data member, and a pointer data member to a character string. Pine1's pointer would have the address of the same data as Pine2's pointer! There would then be two ways of accessing (and modifying!) the same data. This type of a copy operation is called a shallow copy because the "pointed-to" data is not copied when a 'clone' is made. This is not a true clone.

If pointers are part of an object, what you may need is a deep copy which you would have to define yourself. Here is the general syntax for a deep copy constructor.

type :: type (const type  & object_name)
In that example of the general syntax, type refers to the class type name. Notice how the parameter is passed to the copy constructor. You do not want to do any harm to the existing object, so you declare the object parameter as type const and use the ampersand & to pass it as a reference rather than a value. For example:
Tree::Tree(const Tree & otherTree)
    {
    age = otherTree.age;
    descrip = new char[strlen(otherTree.descrip) + 1];
    strcpy(descrip, otherTree.descrip);
    }
Actually, we haven't seen the new operator yet. It defines a dynamic variable in "free store" - a topic of a later lab. However the code is given here for the sake of giving a complete example of a deep copy constructor.

Destructors

Lab Exercise:


CS Dept Home Page
CS Dept Class Files
CS115 Class Files

Copyright: Department of Computer Science, University of Regina.