Aria Ahrafi
Aria Ahrafi

Reputation: 1

Default argument in struct c++

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

Upvotes: 0

Views: 378

Answers (1)

Peter
Peter

Reputation: 36597

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.

Upvotes: 2

Related Questions