1

I get an error if I include the "~Binary_tree()" destructor. But when I remove it, everything compiles.

My node.h file

template<class T>
class Binary_tree
{
    private:
        void insert(T val, Node<T> *ptr);
        Node<T> *search(T val, Node<T> *ptr);
        Node<T> *root;

    public:
        Binary_tree()
        {
            root = NULL;
        }
        ~Binary_tree();
        void insert(T val);
        Node<T> *search(T val);
};

my main.cc

#include<iostream>
#include "node.h"

using namespace std;

int main()
{
    Binary_tree<char> tree;
    return 0;
}
Anton Savelyev
  • 762
  • 7
  • 22

2 Answers2

1

You have not defined your destructor, only declared it. It should be:

~Binary_tree() { /*delete tree*/ }

What you see is actually a linker error, and not compile error. You might think that you have not defined also few other methods like insert or searchand you get no error,... but they are not called in your code - so linker does not output error. On the other hand destructor in your example is called implicitly when tree object goes out of scope. If you dont add one yourself, compiler will create definition on its own - that is why you get no error when you remove declaration of ~Binary_tree();. This compiler synthesized destructor will not free your tree, you have to do it on your own - or use shared ptrs.

marcinj
  • 48,511
  • 9
  • 79
  • 100
0

Template is replacement of macro, so template definition must be available at instantiation point. You should put definition of ~Binary_tree and all other methods to the template definition.

AnatolyS
  • 4,249
  • 18
  • 28