Jonathan Bouchard Jonathan Bouchard - 28 days ago 5
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;
public:
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;
public:
Caisse();
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****/
Magasin.GetCaisses().at(0).AjouterTempsFile(100);
cout << Magasin.GetCaisses().at(0).GetTempsFile() << endl;
/****Does not work****/
}


It's suppose to cout 100, but cout 0

Thanks for helping

Answer

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).

Comments