I really searched the web for this but never came up with an answer. I know two ways of initializing a class and one of them doesn't work when I try to pass a function. Can you help me understand why this happens? And what method should I use? Thanks in advance!
void func(int i){
cout << "GG " << i;
}
class ac{
public:
int a;
function<void()> sh = bind(&func, a);
/*ac (int i){ This does not work
a = i;
}*/
ac (int i) : a(i) {}; // but this does
void go (){
sh();
}
};
int main() {
ac ac1(5);
ac1.go();
return 0;
}
Edit: Thanks for all the responses, this was a lot quicker than I thought. It seems like the output of the first example was some random garbage, I wasn't sure that's why I hesitated to detail the output.
When you do in class initialization it is just a short hand to have that done by the constructor if you do not do it yourself. That means
Becomes
So now we have a default initialized (which in this case means it contains garbage)
a
being used for the function so we have garbage. The reasona
comes beforesh
is that is the way the declred in the class and that dictates the order of initialization.The second example works as the constructor is treated as
And now when we bind
a
tofunc
a
is initialized to an actual value.Binding happens when you call bind.
And
bind
happens in constructor initialization list.So in your code, when your bind the function, you bind it with current value of
a
- which is random unless it was inititalized in constructor initialization list.Does not work since
sh
is initialized using an uninitialized value ofa
.