Problem with pointers, derived classes and vectors

Started by
1 comment, last by Zahlman 13 years, 8 months ago
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();}

My current project: Lyjok's World, an open source, cross-platform horizontal shoot 'em up.

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.
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.

This topic is closed to new replies.

Advertisement