I'm trying to implement a stack and a queue. I've also been provided with a code to test both the stack and a queue (to see whether their respective functions work properly).
I've implemented functions of both the stack and quete,, but when trying to compile them I get the error:
In destructor `Stack::~Stack()'
expected class-name before '(' token
in both of them.
Following is the generic Stack class:
template <class T>
class Stack
{
List<T> list;
public:
Stack();
Stack(const Stack<T>& otherStack);
~Stack();
}
The List class:
template <class T>
class List
{
ListItem<T> *head;
public:
List();
List(const List<T>& otherList);
~List();
}
Now the destructor for the List class is working just fine. So keeping that in mind, my implementation for the destructor was:
template <class T>
Stack<T>::~Stack()
{
list.~List();
}
What am I doing wrong here?
You should (almost) never call a destructor explicitly. When your Stack
's life ends, it will automatically call the destructors of its members. You don't need to do anything. list
will be destroyed automatically.
If you had a pointer, p
, to a dynamically allocated object as a member, then you would need to do some cleaning up in the destructor by doing delete p;
. But here, you don't. list
will be destroyed automatically.
Your list
member is an automatic variable. Its lifetime (the time when its constructor and destructor are callled) is managed by the language. As soon as the containing object goes out of scope, the List
destructor will be called.
That said, there are valid reasons to call a destructor explicitly (you don't have one and you rarely will) and to actually do it you need to specify the type correctly.
In your case that would be
list.~List<T>();
List
itself is a template, not a type.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With