Jonathan Bouchard Jonathan Bouchard - 1 year ago 66
C++ Question

Can't modify object vector in a class

I'm trying to access an object in my vector and change some attributes, but it doesn't modify it. (Sorry for french code)

class Quincaillerie
vector<Caisse> vCaisses;
Quincaillerie(int NBCaisse);
vector<Caisse> GetCaisses() const { return vCaisses; }

Here's the vector vCaisses that I want to access and change

class Caisse
int tempsFile;
int GetTempsFile() const { return tempsFile; }
void AjouterTempsFile(int t) { tempsFile = t; }

Here's the class

Caisse::Caisse() : tempsFile(0)

Quincaillerie::Quincaillerie(int NBCaisse) : vCaisses(NBCaisse, Caisse())

Now when I tried to do this

int main()
Quincaillerie Magasin(NBCAISSES);
/****Here's the problem****/
cout << Magasin.GetCaisses().at(0).GetTempsFile() << endl;
/****Does not work****/

It's suppose to cout 100, but cout 0

Thanks for helping

Answer Source

Try returning a vector<Caisse> & from GetCaisses() instead of vector<Caisse>.

If your GetCaisses() returns a vector<Caisse> by value, only a copy of the vCaisses in the object instance is returned.

So you modify one copy and then query another copy that isn't modified.

You should write a second GetCaisses() that isn't const if you want to modify the returned value; something like

const vector<Caisse> & GetCaisses() const
 { return vCaisses; }

vector<Caisse> & GetCaisses()
 { return vCaisses; }

In this way, GetCaisses() methods return a reference to vCaisees and you can modify it (if you modify the vector received from the not const version).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download