Accessing a member function from a vector of pointers? C++ -
so, lets have vector, vector<item*> vitem
, item class member function item::setvalue();
. lets populated vector using vitem.push_back(new item)
.
now, access member function, through pointer in vector, vitem[0]->setvalue("key");
. valid? assumed was, when cout
member variables using getvalue()
function, nothing new returned, default values constructor.
any ideas? feel it's stupid mistake in logic, i'm not sure. appreciated.
edits:
setvalue code:
void item::setvalue(string svalue) { m_svalue = svalue; }
with private variable:
string m_svalue;
getvalue code:
string item::getvalue() { return m_svalue; }
simple version of 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 note: compiles fine (g++ using c++0x standard) however, setter doesn't set.
your getvalue returns void , there's out-of-place semi-colon after getvalue()
in implementation of method. change string item::getvalue(){return m_svalue;}
Comments
Post a Comment