Stephen Fish
Stephen Fish

Reputation: 75

Creating a template class object using a template constructor

I'm having trouble creating a class object from a template class in which I need the constructor to also be a template and accept a parameter when the object is created. However, when I attempt to create the object, I receive an error message stating that I'm referencing something that doesn't exist.

Here's my code:

using namespace std;
#include <cstdlib>

template <class Node_Type>
class BinaryTree 
{
public:
    BinaryTree(Node_Type);
    BinaryTree(Node_Type, Node_Type);
    BinaryTree(Node_Type, Node_Type, Node_Type);
    bool isEmpty();
    Node_Type info();
    Node_Type inOrder();
    Node_Type preOrder();
    Node_Type postOrder();


private:
    struct Tree_Node
{
    Node_Type Node_Info;
    BinaryTree<Node_Type> *left;
    BinaryTree<Node_Type> *right;
};

Tree_Node *root;

};

#endif

and my .cpp:

template <class Node_Type>
BinaryTree<Node_Type>::BinaryTree(Node_Type rootNode) {

    root = rootNode;
    root->left = NULL;
    root->right = NULL;

}

There's more to the .cpp, but it's just other function members that are irrelevant. My constructor shown above is what I can't get to work.

In my main, I'm attempting to declare my object with the call:

BinaryTree<char> node('a');

but when I try this, I get an error message stating:

undefined reference to `BinaryTree<char>::BinaryTree(char)'

I've been trying to figure this out for two days now. I've Googled every topic I can think of and read countless examples on Stack Overflow and other sources with no help. Can anyone please explain what my problem is? I know how to do my project, and I'd be finished by now if the syntax wasn't so ridiculous in C++. Thanks in advance!

Upvotes: 7

Views: 25693

Answers (3)

QuentinUK
QuentinUK

Reputation: 3077

You can force the instantiation of the template in another cpp file.

BinaryTree<char>;
BinaryTree<int>;
BinaryTree<double>;

That way all the functions do not need to be in header files. Some people use the extension .inl for the files with the template implementations. So the .inl file is only needed when the instantiation doesn't already exist.

Upvotes: 2

stefaanv
stefaanv

Reputation: 14392

Template code should be visible at the time of instantiation, meaning that the definition of the functions must also be in the header.

Upvotes: 10

The Quantum Physicist
The Quantum Physicist

Reputation: 26276

Solution: You can't separate template implementations from the header file. Simply don't use a cpp file and put the definition in your header file (.h file).

Why? This is because cpp files can become precompiled sources, while templates are compile-time objects; therefore, the compiler cannot decide what type to use unless specified. So just put all your template undefined implementations in your header .h file.

Upvotes: 6

Related Questions