1

I have this code:

#include <iostream>

class foo
{
    public:
        foo(int yy){y = yy;}
        void f(int x){std::cout<<x;}

    private:
        int y;
};

void main()
{
    foo* obj = new foo(123);
    void (foo::*func)(int) = &foo::f;

    //how do I call func with obj as this?
    delete obj;
}

Is this possible?

3
  • 2
    This is amply covered in a hundred prior posts, the FAQ, and the Function Pointer Tutorials, so perhaps someone thought you were just being lazy of didn't know how to type anything into Google. Me, I'm outright corrupt and prefer the reputation ;-) Commented Sep 8, 2011 at 18:34
  • I'll agree, but I've done that about 20 times now as a time saver, so +1 to cancel the vote out :p Commented Sep 8, 2011 at 18:42
  • @w00te: it's a sliding scale. Personally, I don't mind answering a concise question if the answer is also short, and often that's indeed a fast method. (In fact, the entire MySQL section seems to work like that.) The question probably hasn't got much "value" because there are easily-findable resources that cover it, but it's an OK question. I'll firmly keep my "no vote" on it :-) Commented Sep 8, 2011 at 18:50

1 Answer 1

3

You call it ike this:

(obj->*func)(42);

The first set of parentheses are needed because of the precedence of "apply function call" over the dereference-PTM ->* operator.

You can also use std::bind:

std::function<void(int)> my_f = std::bind(func, obj, std::placeholders::_1);

my_f(43);
Sign up to request clarification or add additional context in comments.

Comments

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.