3.2 In a class

In a class definition, both data members and the return type of a method can be a reference. Let us observe the following example:

class X
{
    int &whose;
  public:
    X(int &i);
    void set(int i);
    int get(void) const;
    int &there(void);
};

X::X(int &i):whose(i)
{
}

void X::set(int i)
{
  whose = i;
}

int X::get(void) const
{
  return whose;
}

int &there(void)
{
  return whose;
}

void test(void)
{
  int abc;
  X myX(abc);
  myX.set(23);
  cout << myX.get() << endl;
  cout << abc << endl;
  myX.there() = 123;
  cout << abc << endl;
}

Not surprisingly, calling the test subroutine test prints 23 twice. This is because the data member whose is a reference, and it is initialized to be the reference of the variable abc. Consequently, any changes to the data member whose happens to abc itself.

The last value printed is 123 because myX.there() returns a reference, but that reference is specified by the data member whose, which was initialized to be a reference of the variable abc. As a result, the return value of myX.there() is a reference to abc. Since this reference appears on the left hand side of the assignment operator, it specifies where to the store the value of the right hand side, which, of course, is variable abc.

Note that in this example, the compiler generates an error in the following case:

X myOtherX(123);

This is because 123 is an expression, and it does not supply a place to store a value, and so it cannot pass by reference (to the constructor). Well, I am almost right.

Copyright © 2006-09-19 by Tak Auyeung