Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to declare destructor of a templated class

Tags:

c++

I get error while trying to compile following class

Stack.cpp:28: error: expected constructor, destructor, or type conversion before ‘::’ token

#include <iostream>
using namespace std;

template <class T>
class Stack
{
public:
    Stack(): head(NULL) {};
    ~Stack();

    void push(T *);
    T* pop();

protected:
    class Element {
    public:
            Element(Element * next_, T * data_):next(next_), data(data_) {}
            Element * getNext() const { return next; }
            T * value() const {return data;}
    private:
            Element * next;
            T * data;
    };

    Element * head;
};

Stack::~Stack()
{
    while(head)
    {
            Element * next = head->getNext();
            delete head;
            head = next;
      }
 }
like image 966
Jimm Avatar asked May 21 '13 01:05

Jimm


2 Answers

You are declaring a template class. You can either:

  • implement the destructor within the class declaration, like this

    public:
        Stack(): head(NULL) {};
        ~Stack() {
            // ...
        }
    
  • define the templated destructor outside the class declaration, like this

    template <class T>
    Stack<T>::~Stack()
    {
        // ...
    }
    

However, if you attempt to define just Stack::~Stack() then the compiler does not know which type T you are implementing the destructor for.

like image 52
Greg Hewgill Avatar answered Sep 21 '22 06:09

Greg Hewgill


template<typename T>
Stack<T>::~Stack()
{
    //...
}

This is generally valid for every method you define outside of the class' declaration, not just the destructor.

like image 34
Nbr44 Avatar answered Sep 19 '22 06:09

Nbr44