This is the simplest I could work my problem down to, sorry about the length:
#include <vector>
#include <iostream>
class Bar
{
private:
std::vector<int> intVector_;
public:
Bar() {};
void addInt(int newInt)
{
intVector_.push_back(newInt);
std::cout << intVector_.size() << " ";
};
int getIntVectorSize() { return intVector_.size(); };
};
class Foo
{
private:
Bar bar_;
public:
Foo() { bar_ = Bar(); };
Bar getBar() { return bar_; };
};
int main(char argc, char* argv[])
{
Foo foo = Foo();
foo.getBar().addInt(1);
std::cout << foo.getBar().getIntVectorSize() << " ";
foo.getBar().addInt(2);
std::cout << foo.getBar().getIntVectorSize() << " ";
foo.getBar().addInt(3);
std::cout << foo.getBar().getIntVectorSize() << " ";
}
My problem is that adding an int to the vector only seems to last for the duration of addInt(). My output for the size of the vector looks like this:
1 0 1 0 1 0
I’m rather new to C++ and all this reference/pointer business, so I am stumped as to how I can fix this, or if this is even possible. Thanks for any help!
It’s because
getBar()returns aBarby value, which makes a copy ofbar_for every call of the function, and you are modifying the vector of the temporary.You can avoid this by returning a reference:
This way, any modifications done on the return value of
getBarare done onbar_and not a temporary copy that is destroyed at the end of the statement.