5.1 Basic concepts

A constructor is a very interesting member function of a class. Its name must be identical to the class itself. Furthermore, a constructor method has no return type specification (not even void). What makes a constructor method truly special is that it is invoked automatically whenever an object of the containing class definition is created.

Note that constructor methods must be public. We'll talk about this again in another section in this module.

Let us consider an example of how a constructor method is defined:

class X
{
    X(void);
};

X::X(void)
{
  cout << "constructor of X called" << endl;
}

Now, consider the following code to use class X:

X var1; var2;

When var1 and var2 are created (upon the entry of a block), the constructor method is called once for each variable. As a result, the message ``constructor of X called'' is printed twice in this example.

There are many practical needs of a constructor. For example, it can be used to initialize an object to a known/default/safe state. For example:

class Y
{
    int i,j;
    Y(void);
};

Y::Y(void)
{
  i = j = 0;
}



Copyright © 2006-09-26 by Tak Auyeung