Sams Teach Yourself C in 21 Days

(singke) #1
Getting ready to declare myValue...
...In the constructor...
myValue is now declared...
Printing myValue: 99

Ending program.
...In the destructor...
Listing B3.6 creates a simple class called valuethat stores an integer value. A
single private data member is simply an integer that holds a value. In lines 9–10,
you see the constructor and destructor member functions that are a part of this class. You
also can see that a C++ feature you learned about in Day 22 is also being used—default
parameters. The valueconstructor uses a default parameter. If the valueconstructor is
called without the nbrparameter, the value 99 will be the default.

686 Bonus Day 3

OUTPUT

ANALYSIS

Remember that default values can be used with any function in C++. Using
them in constructors is a common practice. This helps to ensure that you
have a value to use.

Note


In lines 35–40, you see the constructor’s definition. This function is called whenever the
value class is used to create an object. You can see that this constructor simply assigns
the parameter that is passed to the object to the valdata member (see line 38). A mes-
sage is then printed out so you can see that the constructor has been entered.
In lines 44–48, you see the valueclass’s destructor definition. For the valueclass, there
is really no need to declare a destructor. The default destructor suffices. This destructor is
created for the purpose of printing a message (line 47) stating that the destructor has
been entered. If you review the output from this listing, you will find it interesting that
the destructor is executed after the Ending programmessage is displayed near the end of
themain()function. The destructor is called when the object is destroyed. In this case,
the object is destroyed when the main()function ends.

Function Overloading Revisited ........................................................................


Yesterday you learned about function overloading. Function overloading can be used in a
number of ways with classes. Specifically, you will find it very valuable to overload a
class’s constructor. Consider the constructor for a dateclass. You could create a number
of constructors that enable you to set up objects by using any number of different for-
mats:

38 448201x-Bonus3 8/13/02 11:19 AM Page 686

Free download pdf