Why Cant i used non-static variables for default argument assiment

1
2
3
4
struct X{
	int var;
	void do_stuff(int i = var){...}//compilers want me to make var static
};
Last edited on
because you are trying to do this:

1
2
3
4
struct X {
	int var = 6;
	void do_stuff(int i = this->var) { int b = i; }
};


and this can only be referenced inside non-static member functions.
Last edited on
and this can only be referenced inside non-static member functions.


Is this a typo? do_stuff() is not static.

P.S. I just want to say thanks for being such a help in the forum
yes, do_stuff() is not static so non-static var can only be referenced within it - not as part of the definition - as the this pointer is only available within the function.
why is the pointer available withing the fucntion only though

1
2
3
4
5
6
int main(){
    X x = {2};
    x.do_stuff(x.var);//here i have access to x.var    
    x.do_stuff((&x)->var);//here i have access to x.var
    x.do_stuff()//here i dont
}
https://en.cppreference.com/w/cpp/language/default_arguments
Non-static class members are not allowed in default arguments (even if they are not evaluated), except when used to form a pointer-to-member or in a member access expression.

1
2
3
4
5
6
7
int b;
class X {
  int a;
  int mem1(int i = a); // error: non-static member cannot be used
  int mem2(int i = b); // OK: lookup finds X::b, the static member
  static int b;
};


That last part means that something like
int mem1(int X::* i = &X::a); would in fact work.
Last edited on
The alternative, by the way, is to use function overloading
1
2
void do_stuff(int i) { /* ... */ }
void do_stuff() { return do_stuff(var); }
Last edited on
@mbozzi oh man you are right


Thanks!!
Last edited on
Topic archived. No new replies allowed.