serg.nechaev
serg.nechaev

Reputation: 1321

std::vector holds base class instance and not of a derived class

I have a problem with C++ vector understanding: an object I get from vector is always a base abstract class and not a derived class that was added to it.

  1. I have a vector:

    vector<SceneNode*> children;
    

Where SceneNode is an abstract class with pure virtual functions.

  1. I add an instance of ImageSceneNode (that is derived from SceneNode) to this vector:

    lib::ImageSceneNode node(static_cast<TextureAsset*>(test));
    
    sceneManager.getRoot()->addChild(&node);
    

Where addChild function is:

   void SceneNode::addChild(SceneNode* child) noexcept {
        this->children.push_back(child);
    }
  1. Later when I iterate the vector the object inside is an instance of SceneNode and fails with a "pure virtual function" call error:

enter image description here

Can you please help, thank you!

Upvotes: 0

Views: 166

Answers (1)

Sneftel
Sneftel

Reputation: 41474

The "pure virtual function call" error is most commonly encountered with an object that has been destroyed. I note that you're grabbing and holding a pointer to node, a variable with local scope. If you're trying to access that object from its pointer in children after the function has exited, you're going to run into errors like this one.

Upvotes: 4

Related Questions