SFML community forums

Help => General => Topic started by: AdrianHEY on April 08, 2021, 09:03:07 pm

Title: Any way I can destroy objects?
Post by: AdrianHEY on April 08, 2021, 09:03:07 pm
I want to make it so if I shoot a bullet and hit something I destroy the bullet and the target. I tried to make it so the object wont draw, but if I don't draw it, it will still be there and kill the enemies so what should i do? I thought of a destructor function of the Bullets class but I have no idea how to use it._.
sorry for the bad english
Title: Re: Any way I can destroy objects?
Post by: Nexus on April 09, 2021, 10:40:04 am
Even if you would call the destructor, the object would still be there, just in a destroyed state. But you'd still have a variable referring to it. Also it would be undefined behavior for stack/automatic objects, their destructor is called at the end of their scope, so don't invoke it manually.

What you typically want to do for things like bullets is a STL container, almost always std::vector (see cppreference.com). You can dynamically add and remove objects, and iterate over all existing objects. So whenever someone shoots a bullet, you add it, and when it hits something, you remove it from the vector.