Okay, you're just trying to create a Linked List that works for only one type of held variable. That's actually really easy, and none of this seperating function and object allocations has anything to do with it.
- In C++, if you use new to allocate an object, the run-time puts the object on a memory structure called the heap.
- The heap for an application is automatically cleaned up only when you exit your application. This is different than java, where all classes must be new'd, and the garbage collector cleans up that memory when there are no more references.
- The pointer you get from a new is a number that references the memory allocated for the object. Pointers have the following states
- NULL. Points to nothing, safe to delete, unsafe to call operations on it
- Valid. Points to a constructed object. Safe to call delete, safe to call operations on it.
- Deleted. Points to memory that has been returned to the heap. Unsafe to call delete or call operations on it.
- Invalid. Points to memory that isn't what the pointer says it is. Unsafe.
- delete, then, needs a pointer to either NULL or a valid object to work. delete is the only way to return memory to the heap. If you no longer need an object created with new, call delete on the pointer that refers to it.
Now, with regard to your code in the original post:
- Comparing pointers just compares the number in the pointer, not the objects it refers to.
What you do is this:
1) You pass in a pointer to an object to be inserted. (let's say its pointer's value is 1)
inObject == 1
2) You check all of your nodes until the you find the tail node in the list (refers to NULL as the next object).
3) You Copy the inserted object (incorrectly, as has been pointed out, use the copy constructor for this, or if neccessary, use the clone idiom).
- the copied object is in a new memory location, indicated by it's pointer.
newObject ==2;
4) You set the pointer of the old tail node to newObject, whose value is 2.
Later, you try to delete.
Assuming you pass in the same pointer as before, inObject ==1
You get to the end of the list, and never encounter an object at 1. Why? Because the pointer you actually put on the list had a value of 2. Object.Delete returns false.
The reason why this next snippet of code works is that you never actually deleted 'object'.
if ( Object.Delete(object) == FALSE ){ object->nextObject = 0;}
If you want your code to work, in Delete, compare the objects by value.
while( *(temp->nextObject) != *objectIn){ temp = temp->nextObject;}
To make that make sense, override the == operator of your Object class to measure semantic equality. If you want to use pointers (same object in memory) to allow deletion, you might consider storing the original pointer of inObject somewhere so that you can refer to it in delete.