Link to home
Start Free TrialLog in
Avatar of kevin_in_va
kevin_in_va

asked on

pointers and memory question

Hi,
I am a novice c++ programmer and I am confused about a couple of issues with pointers and memory allocation.   I have three subquestions concerning a class that contains a pointer member variable, but I don't explicitly assign it to a memory location on the free store using new within the class anywhere.  

Part One:
Do I need to worry about deleting it in the destructor?

 For example, here is a Node class that could be used in a linked list.

class Node
{
public:
Node(): next(0) {};
~Node(); // need to delete next here?
private:
Node * next;  // Here is the pointer in question
double its_length;
};

Now imagine I make a pointer to a Node and allocate it some space on the heap with new:

int main()
{
Node * pNode = new Node;  // Line 3
delete pNode;
pNode = 0;
return 0;
}
Part two :
After the use of new in line three, I have pNode point to an object Node allocated on the free store, is the member variable next now on the free store and do I have to worry about delete within the destructor of Node?  This brings up the point that as the author of the class Node but not the main function necesssarily, I don't know whether the Node objects will be placed on the heap or not.  

Part three:
If I don't need to use delete in this simple example, that means the default copy constructor, and assignment operators are also fine?

Thanks for helping me clear up this confusion!
Avatar of Grass_Hopper
Grass_Hopper

Part 1:
~Node(); // need to delete next here?

I think if you call delete here for "Next",
you will be in effect calling delete on every next node in the list. Unless that is what you want to do, the answer to #1 is no.

Part2:
is the member variable next now on the free store ...

When you call delete on a node, you are freeing the memory for that instance.
The "Next" pointer doesn't need to be deleted.
Pointers are usualy alllocated from the stack, and hold the memory address, in this case of the "node" which is allocated from the heap by calling "new".

Part3:
A pointer to the head of the list should be passed to the constructor to initialise the "Next" member.
If you are creating the first node, you should pass it NULL.

does this make any sense ?
ASKER CERTIFIED SOLUTION
Avatar of Grass_Hopper
Grass_Hopper

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial