Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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".

like image 332
Luke Collins Avatar asked May 31 '26 08:05

Luke Collins


1 Answers

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
};
like image 164
Holt Avatar answered Jun 02 '26 22:06

Holt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!