Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return vector element by reference

Tags:

c++

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?

like image 515
user3242640 Avatar asked Jan 16 '26 18:01

user3242640


2 Answers

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();
like image 77
JaredPar Avatar answered Jan 19 '26 19:01

JaredPar


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...
like image 31
Michael Burr Avatar answered Jan 19 '26 18:01

Michael Burr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!