Search code examples
c++vectorpush-back

push_back private vectors with 2 methods, one isn't working


I have a class with a private vector of doubles. To access or modify these values, at first I used methods such as

void classA::pushVector(double i)
{
this->vector.push_back(i);
}
double classA::getVector(int i)
{
return vector[i];
}

This worked for a while until I found I would have to overload a lot of operators for what I needed, so I tried to change it to get and set the vector directly instead of the values, i.e.

void classA::setVector(vector<double> vector)
{
this->vector = vector;
}
vector<double> classA::getVector()
{
return vector;
}

Now, say there is a classB, which has a private classA element, which also has get and set methods to read and write. The problem was when I tried to push back a value to the end vector in classA.

void classB::setFirstValue(double first)
{
this->getClassA().getVector().push_back(first);
}

This does absolutely nothing to the vector. It remains unchanged and I can't figure out why... Any ideas?


Solution

  • You are returning the vector by value in your getVector(). This means that in your call "this->getClassA().getVector().push_back(first);", you copy the vector, then you push the element on the copy. The copy is then immediately discarded.

    In order to get it work the way you want, you need to return the vector by reference. Your method will look like:

    "vector & classA::getVector()"