Jump to content
  • Advertisement
Sign in to follow this  
M-374 LX

Problem with pointers, derived classes and vectors

This topic is 2858 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

This part is okay:


ObjectExplosion expl;
expl.set( 500, 300 );
objectManager.addObject( &expl );



ObjectExplosion is derived from ObjectBase.
In ObjectManager, I have a vector:


std::vector<ObjectBase*> objects;



I get a segmentation fault if I call a member function from inside ObjectManager:


if ( !objects.empty() )
{
objects[0]->onUpdate();
}

Share this post


Link to post
Share on other sites
Advertisement
It looks like you decided to store a pointer to a local stack variable. The variable gets destroyed after its scope exits and your vector is left holding a pointer to essentially random garbage. You probably want to allocate the variable on the heap with new.

Share this post


Link to post
Share on other sites
Quote:
Original post by M-374 LX
This part is okay:

*** Source Snippet Removed ***]


No, it isn't. As soon as the function ends, 'expl' does not exist any more, and the objectManager's pointer is pointing at garbage.

It looks like you are only using pointers in your vector so that you can get polymorphism. You should instead use some kind of smart pointer, or better yet, use boost::ptr_vector as your container instead of std::vector.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!