Sams Teach Yourself C++ in 21 Days

(singke) #1
Working with Advanced Functions 303

10


15: int itsVal;
16: };
17:
18: Counter::Counter():
19: itsVal(0)
20: {}
21:
22: int main()
23: {
24: Counter i;
25: cout << “The value of i is “ << i.GetItsVal() << endl;
26: return 0;
27: }

The value of i is 0

As it stands, this is a pretty useless class. It is defined on lines 6–16. Its only
member variable is an int. The default constructor, which is declared on line 9
and whose implementation is on line 18, initializes the one member variable,itsVal,
to zero.
Unlike an honest, red-blooded int, the Counterobject cannot be incremented, decre-
mented, added, assigned, or otherwise manipulated. In exchange for this, it makes print-
ing its value far more difficult!

Writing an Increment Function ......................................................................


Operator overloading restores much of the functionality that has been stripped out of this
class. Two ways exist, for example, to add the capability to increment a Counterobject.
The first is to write an increment method, as shown in Listing 10.7.

LISTING10.7 Adding an Increment Operator


1: // Listing 10.7 - The Counter class
2:
3: #include <iostream>
4: using namespace std;
5:
6: class Counter
7: {
8: public:
9: Counter();
10: ~Counter(){}
11: int GetItsVal()const { return itsVal; }

OUTPUT


LISTING10.6 continued


ANALYSIS
Free download pdf