7

I have two functions one of them takes a function as an argument this works just fine, but I want to call this passed function in my second one.

class XY {   
 public:

   void first(void f());
   void second();        
 };

 void XY::first(void f()){

 }

 void XY::second(){
 f(); //passed function from first()
 }
Edgar Rokjān
  • 17,245
  • 4
  • 40
  • 67
Maximilian
  • 754
  • 1
  • 5
  • 26
  • Do you call second from first or do you call second independently at a later point? – NineBerry Feb 25 '17 at 11:47
  • 1
    May want to take a look at this. http://stackoverflow.com/questions/12662891/passing-a-member-function-as-an-argument-in-c – Transzendental Feb 25 '17 at 11:51
  • First gets called one time and second gets called independently later – Maximilian Feb 25 '17 at 11:52
  • 2
    You can then create a member object holding a pointer to void function which first assigns to, and second calls it. – user Feb 25 '17 at 12:00
  • @user yup, a function pointer of the right type would seem to be fine here. `std::function` seems like a tonne of overkill in this case, but people love to suggest it even when none of its special type-erasing features are needed – underscore_d Feb 26 '17 at 23:00

1 Answers1

12

You might use std::function to store the callable and call it later.

class X {
    public:
        void set(std::function<void()> f) {
            callable = f;
        }

        void call() const {
            callable();
        }

    private:
        std::function<void()> callable;
};

void f() {
    std::cout << "Meow" << std::endl;
}

Then create X instance and set the callable:

X x;
x.set(f);

Later call the stored callable:

x.call();
Edgar Rokjān
  • 17,245
  • 4
  • 40
  • 67
  • 3
    upvoted, great c++11 answer, I would only mention that the template is part of the header – user Feb 25 '17 at 12:08
  • @user I omit necessary headers as it is usually done in books and presentations to save space... – Edgar Rokjān Feb 25 '17 at 12:58
  • 1
    Stack Overflow is not space limited in the same way books and presentations are and including preprocessor directives such as `#include` is encouraged. – Captain Obvlious Feb 25 '17 at 16:58