Exploiting References 275
9
yet it is given the address of the SimpleCat. This seriously exposes the original object to
change and defeats the protection offered in passing by value.
Passing by value is like giving a museum a photograph of your masterpiece instead of
the real thing. If vandals mark it up, there is no harm done to the original. Passing by ref-
erence is like sending your home address to the museum and inviting guests to come
over and look at the real thing.
The solution is to pass a pointer to a constant SimpleCat. Doing so prevents calling any
non-constmethod on SimpleCat, and thus protects the object from change.
Passing a constant reference allows your guests to see the original painting, but not to
alter it in any way. Listing 9.11 demonstrates this idea.
LISTING9.11 Passing Pointer to a Constant Object
1: //Listing 9.11 - Passing pointers to objects
2:
3: #include <iostream>
4:
5: using namespace std;
6: class SimpleCat
7: {
8: public:
9: SimpleCat();
10: SimpleCat(SimpleCat&);
11: ~SimpleCat();
12:
13: int GetAge() const { return itsAge; }
14: void SetAge(int age) { itsAge = age; }
15:
16: private:
17: int itsAge;
18: };
19:
20: SimpleCat::SimpleCat()
21: {
22: cout << “Simple Cat Constructor...” << endl;
23: itsAge = 1;
24: }
25:
26: SimpleCat::SimpleCat(SimpleCat&)
27: {
28: cout << “Simple Cat Copy Constructor...” << endl;
29: }
30:
31: SimpleCat::~SimpleCat()
32: {