Return by Reference CSCE 121 J. Michael Moore
Recall Reference Pass by Reference Address to memory location. Treat as if working with direct variable for the memory location. Pass by Reference Pass in the address. Modify calling variable inside function.
Return by Reference Return a reference to an object Modify returned variable after calling function is finished. We’ve already seen this in vector. myVec.at(2) = 7; at() returns a reference and assigns 7 to the memory location in the vector.
If we want to work with a local variable myVec.at(2) = 7; Suppose instead of this we decide we want to work with a variable. int z = myVec.at(2); z = 7; Copies value from the reference and assigns it to z. Setting z to 7, does not change the vector’s value at index 2.
Work with a local reference int& z = myVec.at(2); // or int &z z = 7; z refers to the same memory address as at(2). 7 is assigned to memory address at(2), i.e. the 3rd element in the vector
Writing a function to return by reference struct Chair { int height; } class Room { vector<Chair> chairs; public: void addChair(Chair chair); Chair getChair(int index); Chair Room::getChair(int index) { return chairs.at(index); Returns a copy
Writing a function to return by reference struct Chair { int height; } class Room { vector<Chair> chairs; public: void addChair(Chair chair); Chair& getChair(int index); Chair& Room::getChair(int index) { return chairs.at(index); Returns a reference Chair’s attributes can be modified.