0

What my main doubt is that whenever I try passing the root node as a default value in the insertWord function it throws a compilation error. I do not know where I am going wrong. If somebody could help me. Thank you.

#include <iostream>
#include <string>
using namespace std;

class TrieNode {
 public:
  char data;
  TrieNode** children;
  bool isTerminal;

  TrieNode(char data) {
    this->data = data;
    children = new TrieNode*[26];
    for (int i = 0; i < 26; i++) {
      children[i] = NULL;
    }
    isTerminal = false;
  }

  ~TrieNode() {
    for (int i = 0; i < 26; i++) {
      delete children[i];
    }
  }
};

class Trie {
 private:
  TrieNode* root;

  Trie() { root = new TrieNode('\0'); }

  void insertWord(string word, TrieNode* node = root) {}
};

int main() {
  cout << "Hello World";

  return 0;
}
David G
  • 94,763
  • 41
  • 167
  • 253
  • 4
    Recommendation: When are asking about a compiler diagnostic, reproduce it exactly in text in the question. This removes ambiguity. – user4581301 May 05 '22 at 23:09
  • 2
    In `void insertWord(string word, TrieNode *node = root)`, `root` will be different for each `Trie` instance, thus cannot be used as a default parameter. – user4581301 May 05 '22 at 23:10
  • 1
    Are you sure you want to allow outsiders to be able to screw with the ordering of the trie by selecting a node? – user4581301 May 05 '22 at 23:14
  • 1
    Good reading and a possible answer here:[How to use a member variable as a default argument in C++?](https://stackoverflow.com/questions/9286533/how-to-use-a-member-variable-as-a-default-argument-in-c) – user4581301 May 05 '22 at 23:17

1 Answers1

1

Your compile error

Error C2648 'Trie::root': use of member as default parameter requires static member ConsoleApplication1 C:\work\ConsoleApplication1\ConsoleApplication1.cpp 61

You cannot do this

 void insertWord(string word, TrieNode* node = root) {}

Why would you have a node as part of your user interface anyway, you (the trie) are in charge of where things go. Just remove the argument

 void insertWord(string word) {}

Maybe you are porting non c++ trie code, in that case the root would have to be passed in, but here you have a class member that is the root.

pm100
  • 48,078
  • 23
  • 82
  • 145