0

I want to use a variable as default argument of a function in a struct

for example like this

struct A {   
    int b;  
    A () {  
        b = 0;  
    }  
    int func(int t = b) {  
        ...  
    }  
}  

sorry for bad coding it's my first time posting a question

but I keep getting error and i tried using static int too but i get runtime error.

Is there any way to use b as default argument ?!

when using static int for b i get : (mx is b and wavelet_tree is A)

/tmp/cc3OBfq8.o: In function `main':
a.cpp:(.text+0x2dc): undefined reference to `wavelet_tree::mx'
/tmp/cc3OBfq8.o: In function `wavelet_tree::wavelet_tree()':
a.cpp:(.text._ZN12wavelet_treeC2Ev[_ZN12wavelet_treeC5Ev]+0x42): undefined reference to `wavelet_tree::mx'
/tmp/cc3OBfq8.o: In function `wavelet_tree::build(int*, int, int)':
a.cpp:(.text._ZN12wavelet_tree5buildEPiii[_ZN12wavelet_tree5buildEPiii]+0x66): undefined reference to `wavelet_tree::mx'
a.cpp:(.text._ZN12wavelet_tree5buildEPiii[_ZN12wavelet_tree5buildEPiii]+0x73): undefined reference to `wavelet_tree::mx'
a.cpp:(.text._ZN12wavelet_tree5buildEPiii[_ZN12wavelet_tree5buildEPiii]+0x7f): undefined reference to `wavelet_tree::mx'
collect2: error: ld returned 1 exit status
  • Does this answer your question? [Default arguments as non-static member variables](https://stackoverflow.com/questions/32399730/default-arguments-as-non-static-member-variables) or [Nonstatic member as a default argument of a nonstatic member function](https://stackoverflow.com/questions/4539406/nonstatic-member-as-a-default-argument-of-a-nonstatic-member-function) – walnut Dec 26 '19 at 12:24
  • Regarding the error messages with `static`, see [Undefined reference to static class member](https://stackoverflow.com/questions/272900/undefined-reference-to-static-class-member) or [static variable link error](https://stackoverflow.com/questions/9282354/static-variable-link-error) – walnut Dec 26 '19 at 12:28
  • Even though you mentioned you want the variable as a default value, it's worth mentioning that if the value will not change during run time, you can hard code it as default (let's say the value is 5): `int func(int t = 5)` – SubMachine Dec 26 '19 at 14:25

1 Answers1

2

Simply overload the function

struct A
{   
    int b;  
    A () : b(0) {};

    int func(int t) { return whatever();};
    int func()  {return func(b);};
};

This way, b can be any member of A (whether static or not), or any variable that is accessible where func() is defined, etc.

Peter
  • 32,539
  • 3
  • 27
  • 63