Possible Duplicate:
Why can templates only be implemented in the header file?
I ran into this wall before, but I’ve no idea how to fix it. In g++ I get this error whenever I try to create an object of class BinaryTree:
/home/bej0843/cs261/Assignment1/main.cpp:9: undefined reference to `BinaryTree<char>::BinaryTree()'
Here’s the code for the header file:
#ifndef BINARYTREE_H
#define BINARYTREE_H
#include <iostream>
#include <cstring>
#include <stack>
using namespace std;
template<typename Type>
class BinaryTree
{
public:
struct TreeNode
{
Type nodeinfo;
BinaryTree<Type> *left;
BinaryTree<Type> *right;
};
BinaryTree();
void setInfo(Type a);
void setSubtree(Type a);
bool isEmpty();
Type Info();
void inOrder();
void preOrder();
void postOrder();
virtual ~BinaryTree();
protected:
TreeNode *root;
stack<TreeNode*> s;
stack<TreeNode*> temp;
private:
void postOrder(TreeNode *r);
};
#endif /* BINARYTREE_H */
And here’s the code for its implementation:
#include "BinaryTree.h"
template <typename Type>
BinaryTree<Type>::BinaryTree(){
root = NULL;
}
template <typename Type>
void BinaryTree<Type>::setInfo(Type a){
root->nodeinfo = a;
root->left = NULL;
root->right = NULL;
s.push(root);
}
template <typename Type>
void BinaryTree<Type>::setSubtree(Type a){
root->nodeinfo = a;
root->left->root = s.top();
s.pop();
root->right->root = s.top();
s.pop();
s.push(root);
}
template <typename Type>
bool BinaryTree<Type>::isEmpty(){
return (root==NULL);
}
template <typename Type>
Type BinaryTree<Type>::Info(){
return root->nodeinfo;
}
template <typename Type>
void BinaryTree<Type>::inOrder(){
TreeNode *c;
c = s.top();
while (c!=NULL || (!temp.empty())){
if (c!=NULL)
{
temp.push(c);
c = c->left;
}
else{
c = temp.top();
temp.pop();
cout << c->nodeinfo +" ";
c = c->right;
}
}
}
template <typename Type>
void BinaryTree<Type>::postOrder(){
postOrder(s.top());
}
template <typename Type>
void BinaryTree<Type>::postOrder(TreeNode *r){
temp.push(s.top());
TreeNode *c = temp.top();
s.pop();
postOrder(c->left->root);
postOrder(c->right->root);
cout << c->nodeinfo + " ";
}
template <typename Type>
void BinaryTree<Type>::preOrder(){
TreeNode*c = s.top();
while (c!=NULL||(!temp.empty())){
if (c!=NULL){
cout << c->nodeinfo + " ";
temp.push(c);
c=c->left;
}
else{
c=temp.top();
temp.pop();
c=c->right;
}
}
}
template <typename Type>
BinaryTree<Type>::~BinaryTree(){
}
In main I call:
BinaryTree<char> tree;
and get the error. Help?
You have to place the implementation and declaration of your class in the same file while working with template class.
The compiler needs to generate the code at the same place where template class is used.
Dynamic Allocation in Template Class Constructor
You can do it like this.