Search code examples
c++c++11referencereturn-typemember-functions

problem with variable inside variable reverts once changed changed


I'm having the problem where once I change a variable it seems to be unchanged when referenced later in the code.

class foo
{
private:
    string name;
public:
    foo(string _name)
    :name(_name)
    {}
    void info()
    { cout<<name; }
    void newName(string new_name)
    { name = new_name; }
};

class bar
{
private:
    string _name;
    vector<foo> _content;
public:
    foo at(int i)
    { return _content.at(i); }
    void push_back(foo newFoo)
    { _content.push_back(newFoo); }
};

int main()
{
    foo test("test");
    bar kick;
    kick.push_back(test);
    kick.at(0).newName("nice");
    kick.at(0).info();

    return 0;
}

I would like the program to return "nice" but it returns "test". I imagine this has something to with scope but I do not know. How would I write something that can get around this problem?


Solution

  • This member function

    foo at(int i)
        { return _content.at(i); }
    

    returns a copy of the object stored in the vector.

    If you want to get the expected result then return reference.

    foo & at(int i)
        { return _content.at(i); }
    
    const foo & at(int i) const
        { return _content.at(i); }