简体   繁体   中英

Trying to downcast pointer of object in std::vector

In the constructor of one of my classes I have this line :

m_Projects = std::vector<parent_project>(); //m_Projects type is std::vector<parent_project>
m_Current = nullptr; //m_Current type is parent_project*

In a function of this same class I have this line :

m_Projects.push_back(local_project(TITLE, DEMO, FILE)); //local_project class derives from parent_project class.

In a third function of this same class I have these lines :

m_Current = &m_Projects[0];

if (dynamic_cast<local_project*>(m_Current))

   SetCurrentProject(dynamic_cast<model::local_univariate::local_univariate_project*>(m_Current));

The dynamic_cast returns a null value, but as I understand the cast would be supposed to work since m_Current is a pointer to the first element of m_Projects, which is a local_project object. I think I may be missing something.

as I understand the cast would be supposed to work since m_Current ... is a local_project object.

What you are saying would be true if the vector was containing pointers to parent_project . But as it stores objects, parent_project copy constructor is used to copy your local_project(TITLE, DEMO, FILE) object when being inserted ( push_back ) in the container and then the container stores a parent_project , not a local_project . So m_Current is not a local_project anymore...

You should change m_Projects to be a std::vector<parent_project*> . Then your dynamic cast will work.

m_Projects.push_back(new local_project(TITLE, DEMO, FILE));

m_Current = m_Projects[0];

Make sure you delete the objects when clearing your container to avoid memory leaks then. Or simply use a unique_ptr or shared_ptr .

As commented by Mark Ransom, see What is object slicing?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM