error object returned from stl::map

Hi!

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
    }


the memory could no be read

Any idea why I get the error?

P.D. Sorry for my bad English
The cast on line 13 is not safe for use with polymorphic objects. Use dynamic_cast<testclass *>(i->second).

Note that dynamic_cast<T *> returns a null pointer if the object pointed to by its parameter is not of a subtype of T.
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.
Last edited on
Thaks for the answers. it works !!
Topic archived. No new replies allowed.