Sams Teach Yourself C++ in 21 Days

(singke) #1
When the Cats fall out of scope, their destructors are automatically invoked. The imple-
mentation of the Catdestructor is shown on lines 37–43. deleteis called on both point-
ers,itsAgeand itsWeight, returning the allocated memory to the free store. Also, for
safety, the pointers are reassigned to a null value.

Operator Overloading ..........................................................................................


C++ has a number of built-in types, including int,float,char, and so forth. Each of
these has a number of built-in operators, such as addition (+) and multiplication (*). C++
enables you to add these operators to your own classes as well.
To explore operator overloading fully, Listing 10.6 creates a new class,Counter. A
Counterobject will be used in counting (surprise!) in loops and other applications in
which a number must be incremented, decremented, or otherwise tracked.

LISTING10.6 The CounterClass
1: // Listing 10.6 - 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; }
12: void SetItsVal(int x) {itsVal = x; }
13:
14: private:

302 Day 10


FIGURE10.3
Deep copy illustrated.^5

5

itsAge

old CAT

itsAge

New CAT

Free Store
Free download pdf