"Expected class name" ... Problem in destructor implementation

I am trying to implement a stack and a queue. I've also been provided with code to check both the stack and the queue (to check if their respective functions are working).

I have implemented both stack and quete functions, but when trying to compile them I get the error: In the destructor `Stack :: ~ Stack () 'the expected class name is before' ('token
in both of them.

Below is the generic Stack class:

template <class T>
class Stack
{
    List<T> list;
 public:

    Stack();

    Stack(const Stack<T>& otherStack);

   ~Stack();
}

      

List class:

template <class T>
class List
{
    ListItem<T> *head;

    public:

    List();

    List(const List<T>& otherList);

    ~List();
}

      

Now the List class destructor works fine. So with that in mind, my implementation for the destructor was:

template <class T>
Stack<T>::~Stack()
{

                 list.~List();
}

      

What am I doing wrong here?

+3


source to share


2 answers


You should (almost) never call the destructor explicitly. When your Stack

life is over, it will automatically call the destructors of its members. You don't have to do anything. list

will be automatically destroyed.



If you had a pointer p

to a dynamically allocated object as a member, then you will need to clean up the destructor a bit by doing delete p;

. But you don't do that here. list

will be automatically destroyed.

+6


source


Your member list

is an automatic variable. Its lifetime (the time that its constructor and destructor are accessed) is language driven. As soon as the object containing the object goes out of scope, the destructor is called list

.

However, there are good reasons to explicitly call the destructor (you don't have one, and you rarely will), and in fact you need to specify the type correctly.

In your case it would be



list.~List<T>();

      

list

itself is a template, not a type.

+5


source







All Articles