0

This might seem stupid but please...

class Button{

public:

    void func();

    void Button(void func()){

        //Do something.

        //Like if(something){
    func();
}

    }

};

How do I pass func() as a parameter to Button()?

Thanks in advance!

2 Answers2

1

func cannot be passed into Button as an argument. The parameter of Button is a pointer to function, and pointers to functions cannot point to non-static member functions. func is a non-static member function and it cannot be pointed by a pointer to function.

Solutions:

  • Accept a pointer to member function as the parameter instead of a pointer to function.
  • Make func a non-member function or a static member function which can be pointed by a pointer to function.
eerorika
  • 232,697
  • 12
  • 197
  • 326
  • Oh thanks a lot but I still get this error: `error: return type specification for constructor invalid|`. Does this have to do with something else? –  Sep 27 '21 at 21:43
  • @EEE It's another problem. Your function declaration is a mix of constructor and a regular function syntax. Either remove `void` or change the name of the function to something other than the name of the class. – eerorika Sep 27 '21 at 21:48
0

In C++11 and later, you can use std::function, eg:

#include <functional>

class Button{
public:
    void Button(std::function<void()> func){
        if (something){
            func();
        }
    }
};

This way, you can equally accept any callable type, whether that be a standalone function, a lambda, the result of std::bind(), etc.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
  • Oh thanks a lot but I still get this error: `error: return type specification for constructor invalid|`. Does this have to do with something else? –  Sep 27 '21 at 21:42
  • @EEE That has to do with `Button()` being the same name as the `Button` class, so it gets treated as a class constructor, which can't have a return value specified. Drop the `void` if you really intend for `Button()` to be a constructor. Otherwise, rename `Button()` to something else. – Remy Lebeau Sep 27 '21 at 21:49