Sams Teach Yourself C++ in 21 Days

(singke) #1
Exploiting References 261

9


LISTING9.4 References to Objects


1: // Listing 9.4 - References to class objects
2:
3: #include <iostream>
4:
5: class SimpleCat
6: {
7: public:
8: SimpleCat (int age, int weight);
9: ~SimpleCat() {}
10: int GetAge() { return itsAge; }
11: int GetWeight() { return itsWeight; }
12: private:
13: int itsAge;
14: int itsWeight;
15: };
16:
17: SimpleCat::SimpleCat(int age, int weight)
18: {
19: itsAge = age;
20: itsWeight = weight;
21: }
22:
23: int main()
24: {
25: SimpleCat Frisky(5,8);
26: SimpleCat & rCat = Frisky;
27:
28: std::cout << “Frisky is: “;
29: std::cout << Frisky.GetAge() << “ years old.” << std::endl;
30: std::cout << “And Frisky weighs: “;
31: std::cout << rCat.GetWeight() << “ pounds.” << std::endl;
32: return 0;
33: }

Frisky is: 5 years old.
And Frisky weighs 8 pounds.
On line 25,Friskyis declared to be a SimpleCatobject. On line 26, a
SimpleCatreference,rCat, is declared and initialized to refer to Frisky. On
lines 29 and 31, the SimpleCataccessor methods are accessed by using first the
SimpleCatobject and then the SimpleCatreference. Note that the access is identical.
Again, the reference is an alias for the actual object.

OUTPUT


ANALYSIS
Free download pdf