It is also possible, indeed common, for a class to have more
than one constructor to handle default or special cases, but
we will deal with that later.
At compile time C++ selects which constructor to use for
any specific instantiation of a class, depending on the
specific declaration/definition of the class. C++ has special
rules which help it resolve apparent conflict.
It is possible to write quite bizarre or involved
constructors, but these are not necessarily recommended.
Complex :: Complex (char initial)
if (initial == 'j') {{/* constructor one parameter (a char) */
real = 0;
imaginary = -1;
} else {
real = imaginary = 0;
}
}
This particular simple class does not need a special
destructor, since the normal procedure exit frees local
variables. But had it used new(or malloc) to dynamically
allocate space, then it would need a companion destructor to
give the space back when the object is released. Similarly,
if the constructor opened a file, the companion destructor
would flush and close that file, as well as eliminate all trace
of the object nicely.
|