Return vector element by reference

c++

Solution

The `getElement` method is correctly returning a reference to a `B` instance but the local `ele` is not a reference it is a value. What is essentially happening under the hood here is the following

// Copy constructor B::B(B& other) is being called 
B ele = B(A.getElement());

If you want to `ele` to be a reference then you need to declare it as such

B& ele = A.getElement();

Problem

I have a class A where I want to return a reference to an element in the vector stored in class A. Class A ``` private: vector<B> v; public: B& getElement() { //determine i... return v[i]; } ``` In my main I'm setting a B object to what is return by the getElement() function. However, when I modify it, the vector element isn't being modified main() ``` B ele = A.getElement(); //modify B... ``` What should I be doing differently here?

Original source