everything exept the deleting works. when I try to call the destructor, it just simply removes the linking to other obj. but does not deallocate the memory.
"delete this;" wont work, and I don't know why...
here's the code of my program:
main.cpp
Code:
#include <iostream>
class dyn_obj
{
public:
dyn_obj();
~dyn_obj();
void function(int &);
dyn_obj *prev, *next;
private:
bool del_now;
};
dyn_obj *first_obj = 0, //first object's mem address
*Prev_obj = 0; //the current object's address
dyn_obj::dyn_obj():del_now(false)
{
next = 0;//set the link to the next object to 0, there is no next object yet
if( first_obj == 0 )//if this is the first object in the list
{
first_obj = this;//set this as the first object
prev = 0;//set prev to 0, this are no previous objects.
}
else//if NOT the first object
{
prev = Prev_obj; //link this object to the previous object
prev -> next = this;//link the previous object to this object
}
Prev_obj = this;
}
dyn_obj::~dyn_obj()
{
if(next == 0)
{
if(prev == 0)//if this is the only object existing
{
first_obj = 0; //set first object to 0, no first object
}
else//if this is the last object in the list
{
prev -> next = 0; //remove the linking from the object before
}
}
else
{
if(prev == 0)//if this is the first object in the list
{
first_obj = next; //set the next object as the first one
next -> prev = 0;
}
else//if this object is somewhere in the middle of the list
{
prev -> next = next;//link the previous object to the next one
next -> prev = prev;//and vice versa
}
}
}
void dyn_obj::function(int & value)
{
value++;
if(del_now)delete this;
else del_now = true;
}
int call()
{
int n = 0;
if( first_obj != 0 )//if the list is not empty
{
dyn_obj *object = first_obj;//create a pointer to the first object in the linked list
while( true )
{
object -> function(n);//call the object
if(object -> next != 0) object = object -> next;//if not last object, move to the next one
else break;
}
}
return n;
}
int main()
{
for(int n = 0; n < 10; n++) new dyn_obj;
std::cout << "10 objects created. let's call them." << std::endl;
std::cout << "the function \"function\" was called " << call() << " times." << std::endl;
std::cout << "let's call the functions a second time, making the objects delete themselves." << std::endl;
call();
std::cout << "deleted.";
std::cin.get();
}