Logo Data Structures and Algorithms with Object-Oriented Design Patterns in C++
next up previous contents index

Copy Constructor

  The copy constructor    for an object of class T is the function T::T(T const&). I.e., it is the constructor for objects of class T which takes as its single argument a reference to another object of class T. This constructor builds a copy of the object passed by reference--hence the name copy constructor.

Copy constructors play a crucial rôle in C++ programs. For example, the copy constructor is called automatically by the compiler to pass the value of an actual parameter used in a function call to the formal parameter used in the function definition. Similarly, the copy constructor is called automatically by the compiler to pass the return value from a function back to the caller.

Program gif shows a simple, though perhaps somewhat naıve implementation for the copy constructor of Array<T> class objects. To determine its running time, we need to consider carefully the execution of this function.

   program2714
Program: Array<T> Class Copy Constructor Definition

First, the required amount of memory is allocated by operator new. As discussed above, this involves finding space in the heap, which we assume takes constant time; and then initializing the elements of the array using the default constructor for objects of type T, which takes tex2html_wrap_inline60961. Next, the length field is set to the correct value, which takes constant time.

Finally, the body of the Array<T> constructor is a loop which copies one-by-one the elements of the input array to the newly allocated array. How this copy will actually be done depends on the type T. We shall assume that the running time of this assignment is the same as that of the copy constructor for objects of type T.gif Then, the running time of the main loop of the Array<T> constructor is tex2html_wrap_inline60963 where tex2html_wrap_inline60965 is the time taken by the copy constructor for objects of type T.

Altogether, the running time of the copy constructor for Array<T> is tex2html_wrap_inline60967, where n is the size of the array being copied. In the case where T is one of the built-in types, tex2html_wrap_inline60955 and tex2html_wrap_inline60973, which gives the simple and obvious result, T(n)=O(n).


next up previous contents index

Bruno Copyright © 1997 by Bruno R. Preiss, P.Eng. All rights reserved.