I'm almost done making a 2D game (and yes I'm sorta a newb) and I still haven't figured out how to delete an entity. Instead, as a place holder, I set the texture path to "" and all the variables to 0. I am using a class and here is basically what the code looks like. I don't know if the formatting is completely wrong or what. Please help

class src_entity_vars
{
public:
//some variables and functions here
void kill();
};

void src_entity_vars::kill()
{
// set all values to 0 and sprite path to ""
}

EDIT: Here's some more if I didn't make myself clear

void main()
{
src_entity_vars enemy; // <- this is what I need to delete
if (enemy.health <= 0)
{
enemy.kill;
}
}

void main()

Are you sure this is correct? If so.. why?

your enemy variable is a local, automatic variable. This means it will be destructed when it goes out of scope(do you know what a scope is?).

If you wish to delete the variable at some 'random' point in your code you need to ensure that it goes out of scope at this point OR you need to dynamically allocate the object.

Example:

int myFunction()
{  // start of myFunction scope
    int myInt;
    int* myDynamicInt = new int( 5 );
    while( true )
    { // start of while scope
         int mySecondInt;
    } // end of while scope (mySecondInt is destroyed here).

    delete myDynamicInt; // destroy myDynamicInt
}  // end of myFunction scope (myInt is destroyed here)

If you would have forgotten the 'delete myDynamicInt' in my example, it would cause a memory leak (myDynamicInt would never be cleaned up).

I hope that clears things up a little.

thelamb is right, if you didn't create a new instance of your class (by using the new keyword) then you shouldn't have to manually delete it. You only need to delete something if you dynamically created space for it yourself. Try looking here. Hope this helps.

Thanks guys for a quick response. I wrote a little test code I'm going to try out later on my game... I think i'm doing it right.

#include "stdafx.h"
#include <iostream>
#include <conio.h>
using namespace std;
class enemy
{
public:
	int a;
	int foo(int);
};
enemy * boss = new enemy;
int enemy::foo(int d)
{
	a = d;
	return a;
}

int _tmain(int argc, _TCHAR* argv[])
{
	cout << boss -> foo(8);
	delete boss;
	_getch();
	return 0;
}

Update:
It works on the variables but I need to find a new way to render my sprites cus it somehow gets stuck in a loop.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.