Tibor Móger
Tibor Móger

Reputation: 33

Using a class data-member in a class function as default value, c++

In c++ I'm trying to set a class data as default value for a function in the class, but it throws an error while building it. The code looks like this:

    class tree{
    public:
    node *root;
    bool push(node what, node* current = root, int actualheight = 1){

The compiler throws the error

invalid use of non-static data member 'tree::root' from the location of the function

If I remove the default value of 'current' it works fine. What could be the problem? How could I fix it?

Upvotes: 3

Views: 56

Answers (1)

Jonathan Wakely
Jonathan Wakely

Reputation: 171303

There is no this pointer in the function parameter list, so you can't refer to class members in default arguments.

The solution is to overload the function:

bool push(node what, node* current, int actualheight = 1){...}

bool push(node what){ return push(what, root); }

Now when you call push with one argument it forwards to the other overload, providing root as the second argument, which does exactly what you were trying to achieve.

Upvotes: 6

Related Questions