Why can't I make the object?

I get an error at the build stage "undefined reference to LIST<int>::~List"
I'm trying to learn about templates and my book asked me to make the class into a template then declare the object.
Please show me what I am doing wrong and help me fix the error.Thanks.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
  #include <iostream>

template <class T>
class List
{
private:
public:
    List():head(0),tail(0),theCount(0) {}
    virtual ~List();
    void Insert( int value );
    void append( int value );
    int is_present( int value ) const;
    int is_empty() const { return head == 0; }
    int count() const { return theCount; }
private:
    class ListCell
    {
    public:
        ListCell(int value, ListCell *cell = 0):val(value),next(cell){}
        int val;
        ListCell *next;
    };
    
    ListCell *head;
    ListCell *tail;
    int theCount;
};
  

int main()
{
List <int> myList;
}
You haven't defined the destructor, ~List<T>, or ~List<int> (as you've instantiated List<int>.

By defclaring myList, you're calling the default constructor and destructor.

BTW, are you sure the destructor should be virtual? I don't think it should be.
Last edited on
can you show me how I should define the destructor to get it to compile? thanks.
It should not be virtual to start with.
Make sure to free any allocated memory in the destructor.
ive not used new anywhere, do the ponters count as allocated memory?
this works...

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include <iostream>

template <class T>
class List
{
private:
public:
    List():head(0),tail(0),theCount(0) {std::cout <<"List constructor called.\n";}
    virtual~List(){std::cout<<"List destructor called.\n";}
    void Insert( int value );
    void append( int value );
    int is_present( int value ) const;
    int is_empty() const { return head == 0; }
    int count() const { return theCount; }
private:
    class ListCell
    {
    public:
        ListCell(int value, ListCell *cell = 0):val(value),next(cell){}
        int val;
        ListCell *next;
    };
    
    ListCell *head;
    ListCell *tail;
    int theCount;
};
  

int main()
{
List <int> myList;
}
When you write this in the declaration:
virtual ~List();

you're promising to the compiler that you will write the function
~List();

but you didn't.

Either don't make that promise (by not putting it in the declaration), or fulfil your promise by writing the function ~List();.
Topic archived. No new replies allowed.