0

I have a problem with that error "undefined reference". I can't find any solution to fix that. I just write a simple AVL tree program. My AVL.h

template <class Record>
class AVL_tree {
public:
    AVL_tree();
    ~AVL_tree();
    Error_code insert(const Record &new_data);
    Error_code remove(const Record &old_data);
    bool empty();
    void printLNR();
private:
    Error_code avl_insert(AVL_node<Record> *&sub_root,
                          const Record &new_data, bool &taller);
    Error_code avl_remove(AVL_node<Record> *&sub_root,
                          const Record &old_data,bool &shorter);
    void rotate_left(AVL_node<Record> *&sub_root);
    void rotate_right(AVL_node<Record> *&sub_root);
    void left_balance(AVL_node<Record> *&sub_root,bool &changeHeight);
    void right_balance(AVL_node<Record> *&sub_root,bool &changeHeight);

    AVL_node<Record> *root;
    void destroy(AVL_node<Record> *);
    void printLNR_recursive(AVL_node<Record> *);
};

My AVL.cpp file:

#include <iostream>
#include "AVL.h"
using namespace std;
//---------------------------------------------------------
template <class Record>
AVL_tree<Record>::AVL_tree()
{
    root = NULL;
}
//---------------------------------------------------------
template <class Record>
AVL_tree<Record>::~AVL_tree()
{
    destroy(root);
    root = NULL;
}
//---------------------------------------------------------
template <class Record>
void AVL_tree<Record>::destroy(AVL_node<Record> *subroot) {
    if (subroot != NULL) {
        destroy(subroot->left);
        destroy(subroot->right);
        delete subroot;
    }
}

I just try to create a new obj named Sample in main.cpp but I got this error:

D:/AVL/main.cpp:8: undefined reference to AVL_tree<int>::AVL_tree()' D:/AVL/main.cpp:8: undefined reference toAVL_tree::~AVL_tree()'

My main.cpp file:

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

using namespace std;

int main() {
    cout << "Hello, World!" << endl;
    AVL_tree<int> Bee;

    return 0;
}

1 Answers1

0

Template implementation should be in header visible to main. It is possible to put implementation to source file if you write specializations for all types that you will use in your program.

Pauli Nieminen
  • 1,100
  • 8
  • 7