Search code examples
c++classc++11lambdastd-function

C++ class variable std::function which has default functionality and can be changeable


Need to have a function variable inside the class which have default functionality and it's functionality can be overwritten. Example how I liked/wanted to do(unfortunately unsuccessfully):

#include <iostream>
#include <functional>
using namespace std;

class Base
{
  public:

  std::function<bool(void)> myFunc(){
    cout << "by default message this out and return true" << endl;
    return true;}
};

bool myAnotherFunc()
{
 cout << "Another functionality and returning false" << endl;
 return false;
}

int main()
{
  Base b1;
  b1.myFunc();    // Calls myFunc() with default functionality
  Base b2;
  b2.myFunc = myAnotherFunc;
  b2.myFunc();   // Calls myFunc() with myAnotherFunc functionality
  return 0;
}

I know, this code doesn't compile. Can anyone help to fix this, or recommend something. Don't need to be std::function, if there is another way to implement this logic. Maybe should use lambda?!


Solution

  • Change to:

    class Base {
      public:
      std::function<bool()> myFunc = [](){
        cout << "by default message this out and return true" << endl;
        return true;
      };
    };
    

    Live Demo