Search code examples
c++pointersrecursiondefault-valuesuffix-tree

C++ Default Argument with Pointers


I am writing a program which implements a suffix trie in C++. I am trying to declare a recursive function with no parameters, but which needs to pass a pointer to itself.

I am defining it thus

public:
    string longestRepeat(Node*);

in the header file, and

string Trie::longestRepeat(Node* start = &nodes[0]){
    string deepest = "";
    for(unsigned int i = 0; i < start->getEdges(); i++){
        string child_deepest = longestRepeat(start->getChild(i));
        if(child_deepest.length() > deepest.length())
            deepest = child_deepest;
    }
    return deepest;
}

in the .cpp file, where node is a previously declared data structure.

However simply calling trie.longestRepeat() in the main function results in the error "no matching function call for Trie::longestRepeat(). Candidate expects 1 argument, 0 provided".


Solution

  • You need to put the default parameter in the declaration (in the header file), if you put it on the second declaration (the definition), it will only be used by call that see the second declaration:

    struct Trie {
        std::string longestRepeat(Node*);
    };
    
    int main() {
        Trie{}.longestRepeat(); // Error
    }
    
    std::string Trie::longestRepeat(Node *p = &nodes[0]) { }
    
    void g() {
        Trie{}.longestRepeat(); // Ok
    }
    

    But what you should probably do is create a public version of longestRepeat that calls a private/protected version with &nodes[0]:

    struct Trie {
        std::string longestRepeat() { // No arguments
            longestRepeat_(&nodes[0]);
        }
    private:
        std::string longestRepeat_(Node *); // Real implementation
    };