Function-Call Results

A function call evaluates to an r-value unless the function is declared as a reference type. Functions with reference return type evaluate to l-values, and can be used on the left side of an assignment statement as follows:

#include <iostream.h>

class Point
{
public:
    // Define "accessor" functions as
    // reference types.
    unsigned& x() { return _x; }
    unsigned& y() { return _y; }
private:
    unsigned _x;
    unsigned _y;
};

void main()
{
    Point ThePoint;

    ThePoint.x() = 7;           // Use x() as an l-value.
    unsigned y = ThePoint.y();  // Use y() as an r-value.

    // Use x() and y() as r-values.
    cout << "x = " << ThePoint.x() << "\n"
         << "y = " << ThePoint.y() << "\n";
}
000000

The preceding code defines a class called Point, which contains private data objects that represent x and y coordinates. These data objects must be modified and their values retrieved. This program is only one of several designs for such a class; use of the GetX and SetX or GetY and SetY functions is another possible design.

Functions that return class types, pointers to class types, or references to class types can be used as the left operand to member-selection operators. Therefore, the following code is legal:

class A
{
public:
    int SetA( int i ) { return (I = i); }
    int GetA()    { return I; }

private:
    int I;
};

// Declare three functions:
//  func1, which returns type A
//  func2, which returns a pointer to type A
//  func3, which returns a reference to type A
A func1();
A* func2();
A& func3();

int iResult = func1().GetA();
func2()->SetA( 3 );
func3().SetA( 7 );

Functions can be called recursively. For more information about function declarations, see Function Specifiers and Member Functions. Related material is in Program and Linkage.