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; }