Presentation is loading. Please wait.

Presentation is loading. Please wait.

Return by Reference CSCE 121 J. Michael Moore.

Similar presentations


Presentation on theme: "Return by Reference CSCE 121 J. Michael Moore."— Presentation transcript:

1 Return by Reference CSCE 121 J. Michael Moore

2 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.

3 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.

4 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.

5 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

6 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

7 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.


Download ppt "Return by Reference CSCE 121 J. Michael Moore."

Similar presentations


Ads by Google