Delete Class Object

Hey, I was wondering if someone could help me figure out what methods I could use to delete the individual objects of a class when certain conditions are met.

Currently, I can detect collision between a player class object and a coin class object, but what do I put inside the if(collide) function that will delete currentCoin?

void Triangle::playerCoinCollision(Coin *Coins)
{
for (int i = 0; i < 3; i++) {
Coin currentCoin = Coins[i];
bool collide = false;
// check here if player collides with Coins[i]
if (sqrt(pow(center.x - currentCoin.coinCenter.x, 2) + pow(center.y - currentCoin.coinCenter.y, 2)) < 25) {
collide = true;
}
// if the player collides, set collide = true
if (collide) {

	}
}

}

Hi @JoeDH,

I think you can use something like delete Coins, this should work.
So your code should look somethink like this :


void Triangle::playerCoinCollision(Coin *Coins)
{
    for (int i = 0; i < 3; i++) {
        Coin currentCoin = Coins[i];
        bool collide = false;
    // check here if player collides with Coins[i]
        if (sqrt(pow(center.x - currentCoin.coinCenter.x, 2) + pow(center.y - currentCoin.coinCenter.y, 2)) < 25) {
                collide = true;
        }
        // if the player collides, set collide = true
        if (collide) {
            delete Coins
        }
    }
}

Best,

P

Hi,
What is the Coins container and its data type? Is it a vector or an array?.
In short it should be a vector otherwise you’ll need to deal with some, probably nasty, memory management.
I recommend not instantiating the Coins using the keyword new as that implies that you need to call delete at some point to avoid memory leaks.

If your Coin class allows to simply use std::vector<Coin> Coins; as your collection.
and your collision function should look something like


void Triangle::playerCoinCollision(std::vector<Coin>& Coins)
{
ofRemove(Coins, [&](Coin& coin){
return  (sqrt(pow(center.x - currentCoin.coinCenter.x, 2) + pow(center.y - currentCoin.coinCenter.y, 2)) < 25) ;
});
}