Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 663
Tibor Móger Avatar asked Mar 04 '26 11:03

Tibor Móger


1 Answers

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.

like image 53
Jonathan Wakely Avatar answered Mar 06 '26 02:03

Jonathan Wakely



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!