I have the next code in which i put an object of class 'testclass' ( child class from 'objeto') in a stl::map. Then I search this in the stl::map and return. The problem is when I access a public member of the object returned; in this point the program give me a crash error:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
std::map<std::string, object> loadedObjects;
testclass tst; // testclass se extiende de object
tst.name = "hector";
loadedObjects.insert(std::pair<std::string, object>("gola",tst));
std::map<std::string, object>::iterator i = loadedObjects.find("gola");
if(i == loadedObjects.end())
{
cout<<"not found anything"<<endl;
}
else
{
cout<<i->first<<endl;
testclass* tst2 = (testclass*) &i->second;
cout<< tst2->name<<endl; //crash error in this point
}
If you want to store object of derived type through the base class using a standard container then you will want to have the container hold pointers to the base class. By stored base class objects, when you insert a derived (I'm assuming testclass is derived from object) then you will suffer from object splicing. Which means that only the base part of the derived object will be copied into the container. I assume that ->name is referring to a member of the derived class, or referring data from a derived class, which will crash because memory was not copied for the derived portion of the object.