Why does following C++ code gives below mentioned error? Also why is not this the idiomatic way of writing recursive data-structures in C++? Is there something fundamentally wrong with this way of writing C++?
#include<iostream>
using namespace std;
class tree{
public:
virtual void inorder() {};
};
class emp_tree: public tree{
public:
void inorder(){
}
};
class non_emp_tree: public tree{
public:
tree left, right;
int val;
non_emp_tree(int v, tree l, tree r): val(v), left(l), right(r) {};
void inorder(){
left.inorder();
cout<<" "<<val<<" ";
right.inorder();
}
};
int main() {
tree leaf1 = non_emp_tree(1, emp_tree(), emp_tree());
tree leaf2 = non_emp_tree(3, emp_tree(), emp_tree());
tree root = non_emp_tree(2, leaf1, leaf2);
root.inorder();
return 0;
}
Error given by compiler: (I'm unable to comprehend most of it)
/tmp/ccAjhirw.o: In function `main':
b_t.cpp:(.text+0x16e): undefined reference to `tree::inorder()'
/tmp/ccAjhirw.o: In function `tree::tree()':
b_t.cpp:(.text._ZN4treeC2Ev[_ZN4treeC5Ev]+0x9): undefined reference to `vtable for tree'
/tmp/ccAjhirw.o: In function `tree::tree(tree const&)':
b_t.cpp:(.text._ZN4treeC2ERKS_[_ZN4treeC5ERKS_]+0xd): undefined reference to `vtable for tree'
/tmp/ccAjhirw.o: In function `non_emp_tree::inorder()':
b_t.cpp:(.text._ZN12non_emp_tree7inorderEv[_ZN12non_emp_tree7inorderEv]+0x19): undefined reference to `tree::inorder()'
b_t.cpp:(.text._ZN12non_emp_tree7inorderEv[_ZN12non_emp_tree7inorderEv]+0x56): undefined reference to `tree::inorder()'
/tmp/ccAjhirw.o: In function `tree::tree(tree&&)':
b_t.cpp:(.text._ZN4treeC2EOS_[_ZN4treeC5EOS_]+0xd): undefined reference to `vtable for tree'
/tmp/ccAjhirw.o:(.rodata._ZTI12non_emp_tree[_ZTI12non_emp_tree]+0x10): undefined reference to `typeinfo for tree'
/tmp/ccAjhirw.o:(.rodata._ZTI8emp_tree[_ZTI8emp_tree]+0x10): undefined reference to `typeinfo for tree'
collect2: error: ld returned 1 exit status
Edit: I changed virtual void inroder()
to virtual void inorder() {}
i.e empty implementation. But still I am not getting desired output, it seems root, leaf1 and leaf2 are both calling tree's inorder not their respective inorders.