views:

59

answers:

2

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?

+3  A: 

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()"

small_duck
While this is the reason for the behaviour the OP experiences, one shouldn't pass non-const references to internal data.jmclem, you should contemplate how much access to the data you store in your vector users of classA really need and implement the necessary functions as members of classA directly.
haffax
worked perfectly, thank you. As haffax said, the consts had to be removed. I'll see what to do about that. Maybe the elements don't need to be private, but I was trying to form a "good" structure. Maybe this is not the best way to do it.Thanks for your help!
jmclem
+2  A: 

In this method:

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

you are passing a copy of the vector. To pass the actual vector, you need a reference:

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

and the vector variable in your class will have to be a pointer.

This all looks pretty undesirable to me - I would rethink what your class is actually doing. It makes much more sense for the class to manage the vector than for it to maintain a pointer to one outside the class. and if you need to re-implement all the class methods, maybe you don't need te class at all, but just a vector.

anon
jmclem
@jmclem Just about everything you say in that comment is wrong.
anon
That's quite possible, since I only started with C++ (and programming in general) a while ago. It did work without pointers, though.
jmclem