I am trying to call virtual method at the constructer of parent class and I want to that of child methods. Let me explain:
I need to read words from line by line from a text file and insert them a search tree one by one. I have tree child classes: DictionaryBST
,DictionaryAVLTree
,Dictionary23Tree
. I implemented their own insert methods.
Here the header code of my parent class which is DictionarySearchTree:
class DictionarySearchTree {
public:
DictionarySearchTree();
DictionarySearchTree(string dictionaryFile);
virtual ~DictionarySearchTree();
virtual void insert(string word);
virtual void search(string word, int& numComparisons, bool& found) const;
virtual void search(string queryFile, string outputFile) const;
virtual void inorderTraversal();
protected:
TreeNode* root;
int size;
void searchNode(TreeNode* node, string word, int& numComparisons, bool& found) const;
void virtual insertNode(TreeNode*& node, string word);
void postTraversalDeletation(TreeNode*& node);
void inorder(TreeNode* node);
void getHeight(TreeNode* node, int& height);
};
Here is the constructer:
DictionarySearchTree::DictionarySearchTree(string dictionaryFile) {
root = NULL;
size = 0;
istringstream stream;
ifstream infile;
string line;
infile.open(dictionaryFile);
while (getline(infile, line)) {
insert(line); // This methods should call child's ones.
}
infile.close();
}
My main method:
int main() {
DictionarySearchTree* tree = new DictionaryBST("./dictionary.txt");
DictionarySearchTree* avlTree = new DictionaryAVLTree("./dictionary.txt");
DictionarySearchTree* twoThreeTree = new Dictionary23Tree("./dictonary.txt");
}
I don't want to write constructer methods to each one, as well. Can some help me?
dynamic_cast
ing thethis
pointer won't work inside the base class's constructor and destructor. – Remy Lebeauthis
object simply does not exist yet, it hasn't even started being constructed yet, while the parent constructor is running, thus you can't call child methods on it. You have to wait until the child constructor is running/exited before you can call any child methods on the object. – Remy Lebeau