0

how to properly address this?

 class House{
 public:
  void startAction();
  void init(){
      startAction = [] () {}; 
  }  
 };

I have tried this, but it is said "Expression is not assignable"

I want to define the function of startAction, but inside the init method.

I do this because there's couple of variable in init method that i want to capture to pass to startAction.

7
  • use std::function for startAction Commented Jul 3, 2014 at 9:28
  • 1
    why not capture the values in House? The values seemed to be owned by it, from your description Commented Jul 3, 2014 at 9:36
  • thanks, I really don't want to capture it in House, as i want to destroy it as init end. Commented Jul 3, 2014 at 9:45
  • Is there a rationale behind that two-step construction? Commented Jul 3, 2014 at 9:51
  • @GulperEeL It doesn't really matter whether you store those values as members in the object or in the function's closure. The only difference is whether they're accessible from other member function sor not. Commented Jul 3, 2014 at 19:36

3 Answers 3

6

You can't assign a value to a member function.

You could have a member variable that the member function calls, something like this:

class House{
 public:
  void startAction() { m_action(); }
  void init(){
      m_action = [] () {}; 
  }
 private:
  std::function<void()> m_action;  
};

But it's simpler to store the things you want to capture as members of House.

Sign up to request clarification or add additional context in comments.

Comments

5

Try this:

class House {
  public:
    std::function<void ()> startAction;
    void init() {
        startAction = []() {};
    }  
};

int main() {
    House house;
    house.init();
    house.startAction();
    ...
}

Comments

0

You can also instead of using std::function<void ()> use C style pointer to function. Look at the following code.

#include <iostream>

typedef void (*my_func)();

class House
{
public:
    my_func  m_ffunc;

    void init()
    {
        m_ffunc = [](){ std::cout << "Hello from m_ffunc" << std::endl;};
    }
};

int main()
{
    House myHouse;

    myHouse.init();
    myHouse.m_ffunc();

    return 0;
}

1 Comment

"there's couple of variable in init method that i want to capture". C-style pointers to function cannot capture variables. This doesn't answer the question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.