srt1104
srt1104

Reputation: 959

Error while passing a private data member as default argument to a public method of that class

I think the title says it all. The error MSVS showing is

a nonstatic member reference must be relative to a specific object

My code:

struct Node
{
    Node(size_t id, int length, int size);
    size_t id_;
    int length_;
    std::vector<Node*> children_;
};

class SuffixTree
{
public:
    SuffixTree();
    void printSuffixes();
    void printSuffixes(Node* current = root_);    // ERROR
    ~SuffixTree();
private:
    Node *root_;
};

There are a few more methods similar to these such that I want the user to call these methods from main but since root_ is private, I had to overload all those methods and the user now calls the overloaded methods instead. The definition of these methods are simply like:

void SuffixTree::printSuffixes()
{
    printSuffixes(root_);
}

Any solution?

Edit:

void SuffixTree::printSuffixes(Node* current)
{
    if (current == nullptr)
        return;
    if (current->length_ == -1)
        std::cout << "leaf" << std::endl;
    for (size_t i = 0; i < current->children_.size(); ++i)
        printSuffixes(current->children_[i]);
}

Upvotes: 0

Views: 46

Answers (1)

Acorn
Acorn

Reputation: 26066

Default arguments have quite a few restrictions.

Instead, consider using nullptr as the default:

void SuffixTree::printSuffixes(Node* current = nullptr)
{
    if (current == nullptr)
        current = root_;
    // ...
}

Upvotes: 1

Related Questions