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

Constructors and Destructors

A constructor  is a member function that has the same name as its class (and which has no return value). E.g., there are four constructors declared in Program gif (lines 6-9). The purpose of a constructor is to initialize an object. In fact, C++ makes the following promise: If a class has a constructor, all objects of that class will be initialized.

Consider the following sequence of variable declarations:

Complex c;       // calls Complex ()
Complex d = 2.0; // calls Complex (double)
Complex i(0, 1); // calls Complex (double, double)
Complex j(i);    // calls Complex (Complex const&)
Each variable declaration implicitly causes the appropriate constructor to be invoked. In particular, the equal sign in the declaration of d denotes initialization not assignment and, therefore, is accomplished by calling the constructor.




next up previous contents index

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