References to Objects

It is possible to pass an object to a function by value or by reference. When passing by value (traditionally) a copy of an object is created when the function is entered and when the function is exited the object’s destructor is called. When an object is passed by reference, no copy is made, hence no destructor is called upon exiting the function. A reference can also be returned. Of course, the object being returned as a reference must not go out of scope once the function has exited. Further, when a function returns the reference to an object, it can be assigned a value, which will actually be assigned to the object returned as a reference. A program follows in which a function multiply takes the reference to an object as an argument and returns the reference to the same object.

Example


#include <iostream>
#include <string>

using namespace std;

class AClass {
private:
    int a;

public:
    void seta(int x) {
        a = x;
    }

    int geta() {
        return a;
    }
};

// returns a reference and gets a reference as an argument
AClass &multiply(AClass &anObject, int x) {
    anObject.seta(anObject.geta() * x);
    return anObject;
}

int main() {
    // create two objects
    AClass obj1; 
    AClass obj2;

    obj1.seta(12);       // set obj1's a to 12
    multiply(obj1, 10);  // multiply the reference by ten
    cout << obj1.geta() << endl;

    obj2.seta(700);           // set a for obj2
    multiply(obj1, 3) = obj2; // assign obj2 to the reference of obj1
    cout << obj1.geta() << endl;
}

Output

120
700