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?
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();
This code:
B ele = A.getElement();
//modify B...
makes a copy of the element returned by reference from A.getElement() into ele.
If you want ele to refer to the element in A then try:
B& ele( A.getElement());
//modify ele...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With