|

Any
object can be referenced, including user-defined
objects. Note that you create a reference to an
object, but not to a class. You do not write this:
int
& rIntRef = int; // wrong
You
must initialize rIntRef to a particular integer,
such as this:
int
howBig = 200;
int
& rIntRef = howBig;
In
the same way, you don’t initialize a reference to
a CAT:
CAT
& rCatRef = CAT; // wrong
You
must initialize rCatRef to a particular CAT object:
CAT
frisky;
CAT
& rCatRef = frisky;
References
to objects are used just like the object itself.
Member data and methods are accessed using the normal
class member access operator (.), and just as with
the built-in types, the reference acts as an alias
to the object. Listing 9.4 illustrates this.
Listing
9.4. References to objects.
1:
// Listing 9.4
2:
// References to class objects
3:
4:
#include <iostream.h>
5:
6:
class SimpleCat
7:
{
8:
public:
9:
SimpleCat (int age, int weight);
10:
~SimpleCat() {}
11:
int GetAge() { return itsAge; }
12:
int GetWeight() { return itsWeight; }
13:
private:
14:
int itsAge;
15:
int itsWeight;
16:
};
17:
18:
SimpleCat::SimpleCat(int age, int weight)
19:
{
20:
itsAge = age;
21:
itsWeight = weight;
22:
}
23:
24:
int main()
25:
{
26:
SimpleCat Frisky(5,8);
27:
SimpleCat & rCat = Frisky;
28:
29:
cout << "Frisky is: ";
30:
cout << Frisky.GetAge() << " years old.
\n";
31:
cout << "And Frisky weighs: ";
32:
cout << rCat.GetWeight() << " pounds.
\n";
33:
return 0;
34:
}
OUTPUT:
Frisky is: 5 years old.
And Frisky weighs 8 pounds.
ANALYSIS: On line 26, Frisky is declared
to be a SimpleCat object. On line 27, a SimpleCat
reference, rCat, is declared and initialized to
refer to Frisky. On lines 30 and 32, the SimpleCat
accessor methods are accessed by using first the
SimpleCat object and then the SimpleCat reference.
Note that the access is identical. Again, the reference
is an alias for the actual object.
|