DreamTool DreamTool - 1 month ago 5
C++ Question

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.

Answer

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. Make sure you delete the objects when clearing your container to avoid memory leaks then.

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

m_Current = m_Projects[0];

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