-1

I want to know why control does not go to AB() if I pass in abc(AB) into main() as control goes for initialization of i as 10 when abc(10) is passed

class abc
{
    int i;
        
    std::function<void(void)>func = nullptr;
public:
    abc(){}
        
    abc(std::function<void(void)>&fb):func(fb){}
    
    abc(int i):i(i){}
};

void AB()
{
    cout<< "fun_AB";
}

int main()
{
    abc(AB);
    abc(10);
}
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459

2 Answers2

0

Your constructor is called with AB which is a function:

abc(std::function<void(void)>&fb) : func(fb) {}

This initializes func to point to AB, but nothing more. Perhaps you wanted to call it:

abc(std::function<void(void)>&fb) : func(fb) { func(); }
John Zwinck
  • 239,568
  • 38
  • 324
  • 436
0
abc(AB);

This is a declaration of a variable of type abc named AB, equivalent to abc AB;. So the no-arg constructor is called. You could use this syntax if you don't want to name the variable:

abc{AB};

This "works" since it can't be parsed as a declaration, while your version can.

But that's not enough, you need to change your constructor to accept a const&:

abc(std::function<void(void)> const& fb) : func(fb)
{
  func(); // if you want AB to be called
}

(Non-const reference won't bind to a temporary.)

Mat
  • 202,337
  • 40
  • 393
  • 406