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

The Copy Constructor, Parameter Passing and Function Return Values

The copy constructor plays a special rôle in pass-by-value parameter passing. As discussed in Section gif, the semantics of pass-by-value stipulate that the the values of the actual parameters are used to initialize the formal parameters when a function is called. The compiler achieves this by using the copy constructor to copy the value of the actual parameter to the formal parameter.

The copy constructor plays a similar rôle when a value is returned from a function using the return statement. The copy constructor is used to copy the value from the called function back to the point where the calling function makes use of the result.

Program gif gives an implementation for the copy constructor of the Complex class. The copy constructor initializes the the member variables real and imag by calling explicitly their respective copy constructors (line 14). After the member variables have been initialized, the body of the constructor runs. In this case, the body of the copy constructor is empty (line 15).


next up previous contents index

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