1

Possible Duplicate:
C++ member-function pointer
How to invoke pointer to member function when it's a class data member?

I've only recently started using C++, so I apologize if the following contains any trivial mistakes, or if I missed an easier solution. I would like to achieve something like this:

class ClassA {

typedef double (ClassA::*CondFunc)();
 public:
    ClassA(int x, int y) {

        value_ = x;

        switch (y) {
            case 0:
                condFunc_ = &ClassA::condA;
                break;
            case 1:
                condFunc_ = &ClassA::condB;
            default:
                break;
        }
    }

    ~ClassA();

    int value_;
    CondFunc condFunc_;
    double condA() { return 2.0*value_; }
    double condB() { return 4.0*value_; }

    void Test() {
        int a = condFunc_(); // compile error
    } 
};

but get a compile error in Test(). Please note that this is a vastly simplified function and is not supposed to make any sense. I've searched this forum and elsewhere for answers, but am still not sure whether defining/calling such non-static member function pointers is even possible. The only plausible hint/solution I've come across employs a static wrapper function to achieve something similar. I'd be grateful for any help/clarifications.

6
  • 2
    It's terribly useful in the case of compiler errors to list the actual error message you're receiving. Commented Mar 12, 2012 at 3:55
  • My immediate reaction is that we could probably help more if you would take a step back (so to speak) and tell us a bit more about what you're trying to accomplish. In roughly 25 years of using C++, I could probably count all the times I've used pointers to member functions on my fingers. Commented Mar 12, 2012 at 3:56
  • The compiler error I get is (with Xcode): Called object type 'CondFunc' (aka 'double (ClassA::*)()') is not a function or function pointer. As for the reason I'm trying to do this: partial functionality of the member function must depend on 'y'; in the actual function this is called within a loop, and I wanted to avoid a switch. Commented Mar 12, 2012 at 4:08
  • @iammilind No, since the assignment happened within the member function, and not on an instantiated object Commented Mar 12, 2012 at 4:12
  • @JerryCoffin Seeing that the solution wasn't easy to find, I suspected that I may not be doing this in the most straightforward fashion. What would your suggestion be to achieve the same functionality/code structure? Commented Mar 12, 2012 at 4:47

1 Answer 1

4

You have to call the member pointer function like this:

    int a = (this->*condFunc_)(); 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.