Sams Teach Yourself C++ in 21 Days

(singke) #1
The default constructor and destructor created by the compiler don’t have arguments. In
addition, they don’t appear to do anything! If you want them to do something, you must
create your own default constructor or destructor.

Using the Default Constructor........................................................................


What good is a constructor that does nothing? In part, it is a matter of form. All objects
must be “constructed” and “destructed,” and these do-nothing functions are called as a
part of the process of constructing and destructing.
To declare an object without passing in parameters, such as
Cat Rags; // Rags gets no parameters
you must have a constructor in the form
Cat();
When you define an object of a class, the constructor is called. If the Catconstructor
took two parameters, you might define a Catobject by writing
Cat Frisky (5,7);
In this example, the first parameter might be its age and the second might be its weight.
If the constructor took one parameter, you would write
Cat Frisky (3);
In the event that the constructor takes no parameters at all (that is, that it is a defaultcon-
structor), you leave off the parentheses and write
Cat Frisky;
This is an exception to the rule that states all functions require parentheses, even if they
take no parameters. This is why you are able to write
Cat Frisky;
This is interpreted as a call to the default constructor. It provides no parameters, and it
leaves off the parentheses.
Note that you don’t have to use the compiler-provided default constructor. You are
always free to write your own default constructor—that is, a constructor with no parame-
ters. You are free to give your default constructor a function body in which you might
initialize the object. As a matter of form, it is always recommended that you define a
constructor, and set the member variables to appropriate defaults, to ensure that the
object will always behave correctly.

154 Day 6

Free download pdf