Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Expected class-name"...Issue in destructor implementation

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?

like image 879
mrsinister Avatar asked Dec 15 '22 14:12

mrsinister


2 Answers

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.

like image 158
Joseph Mansfield Avatar answered Jan 19 '23 10:01

Joseph Mansfield


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.

like image 42
pmr Avatar answered Jan 19 '23 09:01

pmr