Hi all,

I'm new to C++ after having worked with c# and java for a number of years.
I'm having trouble getting my head around destructors and their proper use.

take for example this problem i'm working on at the moment.

you have a double linked list centered around a template class called node.

template<class DataType>
class Node
{
private:
	const DataType& fValue;
	Node<DataType>* fNext;
	Node<DataType>* fPrevious;

public:
	Node (const DataType& aValue,
			Node<DataType>* aNext = (Node<DataType>*)0,
			Node<DataType>* aPrevious = (Node<DataType>*)0) : fValue(aValue)
	{
		fNext = aNext;

		fPrevious = aPrevious;
		if(aPrevious != ((Node<DataType>*)0))
		{
			aPrevious->fNext = this;
		};

	};

	~Node()
	{
		//keeps the integrity of the list if this node is deleted
		fPrevious->fNext = fNext;
		fNext->fPrevious = fPrevious;
		
		//pointer managment? what should happen to the pointers fPrevious and fNext?
		
	};
	
	const DataType& GetValue() const
	{
		return fValue;
	};
	const Node<DataType>* GetNext() const
	{
		return fNext;
	};
	const Node<DataType>* GetPrevious() const
	{
		return fPrevious;
	};
};

the list is to be tested in a loop, then a node is deleted with the c++ delete keyword
and the loop is carried out again on the remaining nodes.

output should be (three nodes, values 1, 2, 3)

1
2
3

deleting 2

1
3

so list integrity must be maintained, logic for this would be in the destructor i assume.

my main question is what needs to happen in the destructor to the pointers fPrevious and fNext.

if you could give me a hand that'd be fantastic.

Recommended Answers

All 3 Replies

The use of destructor is to delete or release any memory that has been
allocated. In Java, they handle the garbage collection for you. C++
is not as friendly. You have to use the destructor to delete or handle
anything that needs to be handled when the object gets destroyed.
As your double linked list example, you will use new to allocate new
memory. When the double linked list gets destroyed, its destructor
will be called. And in the destructor you will have to write the code
to delete the whole list.

>The use of destructor is to delete or release any memory that has been allocated.

Nope. It is a method which is automatically invoked when the object is destroyed.

>The use of destructor is to delete or release any memory that has been allocated.

Nope. It is a method which is automatically invoked when the object is destroyed.

Yes I said that here " When the double linked list gets destroyed, its destructor will be called."

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.