Search code examples
c++classparametersdefaultmembers

c++ default parameters class members


class bst
{
private:

typedef struct nod
{
  int data;
  nod* left;
  nod* right;
  nod(int key):data(key),left(NULL),right(NULL){}
}node;
 node* root;

public:

void create();
void add(int key,node*curr=root);
void c2ll();
void print(){}

The code doesn't compile... I get the below errors.

ain.cpp: In function ‘int main()’:
main.cpp:7:12: error: call to ‘void bst::add(int, bst::node*)’ uses the default argument for parameter 2, which is not yet defined
   bt.add(50);
            ^
In file included from bst.cpp:1:0:
bst.h:14:8: error: invalid use of non-static data member ‘bst::root’
  node* root;
        ^
bst.h:19:28: error: from this location
 void add(int key,node*curr=root);
                            ^
bst.h:14:8: error: invalid use of non-static data member ‘bst::root’
  node* root;
        ^
bst.cpp:10:34: error: from this location
 void bst::add(int key,node* curr=root)

Any suggestions would be welcome...I am trying to avoid writing a wrapper method and instead use the default functionality provided by c++


Solution

  • According to the C++ Standard (8.3.6 Default arguments)

    1. ...Similarly, a non-static member shall not be used in a default argument, even if it is not evaluated, unless it appears as the id-expression of a class member access expression (5.2.5) or unless it is used to form a pointer to member (5.3.1). [ Example: the declaration of X::mem1() in the following example is ill-formed because no object is supplied for the non-static member X::a used as an initializer.
    int b;
    class X {
    int a;
    int mem1(int i = a); // error: non-static member a
    // used as default argument
    int mem2(int i = b); // OK; use X::b
    static int b;
    };
    

    You could overload function add. For example

    void add( int key );
    
    void add( int key, node *curr );
    

    The first function would use root by default. It could simply call the second function passing as the second argument the node root.