Reputation: 33
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?
Upvotes: 3
Views: 2257
Reputation: 311126
Using this statement
B ele = A.getElement();
object ele contains a copy of an element of the vector. You should use a reference to an element of the vector
B &ele = A.getElement();
But take into account that the reference can became invalid if for example the vector will be resized. So it is better to change an element of the vector in one statement with the function call. For example
A.getElement() = SomeNewValue;
Also you could overload operator [] for the class. In this case the code could look as
A a;
a[i] = SomeNewValue;
Upvotes: 0
Reputation: 340476
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...
Upvotes: 2
Reputation: 755457
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();
Upvotes: 6