0

So, lets say I have a vector, vector<Item*> vItem and an Item class with a member function Item::setValue();. Lets also say I populated that vector by using vItem.push_back(new Item).

Now, to access that member function, through the pointer in the vector, would vItem[0]->setValue("key");. be valid? I assumed it was, however when I cout the member variables using a getValue() function, nothing new is returned, only the default values from my constructor.

Any ideas? I feel like it's a stupid mistake in my logic, but I'm not sure. Any help would be greatly appreciated.

EDITS:

setValue code:

void Item::setValue(string sValue)
{
        m_sValue = sValue;
}

with the private variable:

string m_sValue;

getValue code:

string Item::getValue()
{
    return m_sValue;
}

Simple version of the code:

void func2(vector<Item*>& vItem)
{
    vItem.push_back(new Item);
    vItem[0]->setValue("key");
}

int main(int argc, char * argv[])
{
    vector<Item*> vItem;
    func2(vItem);
    cout << vItem[0]->getValue() << endl;

    return 0;
}    

I should also note: everything compiles just fine (g++ using c++0x standard) however, the setter just doesn't set.

Nick
  • 25
  • 3

1 Answers1

0

Your getValue returns a void and there's an out-of-place semi-colon after getValue() in your implementation of that method. Change to string Item::getValue(){return m_sValue;}

czifro
  • 784
  • 7
  • 24
  • My apologies, I accidentally set it as void on here. I did correctly set it as a string in the real program. Thanks though – Nick Oct 07 '13 at 02:38
  • you still have an added semi-colon. `string Item::getValue();` – czifro Oct 07 '13 at 02:45
  • I tested your code, and it runs fine and outputs the expected result. To check that the setter is working right, cout the private string var at the end of your setValue method to ensure that m_sValue = sValue – czifro Oct 08 '13 at 00:48