user1296259
user1296259

Reputation: 521

How to assign a member function to a pointer to member function in C++

I'm trying to assign a member function to a pointer to a member function in C++, but I am getting an error. I have code like this:

#ifndef MY_CLASS_H
#define MY_CLASS_H

class MyClass {
    MyClass* (MyClass::*memPtr_) (ParamType);
public:
    void myFunction();
    void myFunction2();
    void myFunction3();

    MyClass& foo(ParamType var);
    MyClass& bar(ParamType var);
    MyClass& fooBar(ParamType var);
    ...
};

#endif

and...

void MyClass::myFunction() {
    memPtr_ = &MyClass::foo;

...

void MyClass::myFunction2() {
    memPtr_ = &MyClass::bar;

...

void MyClass::myFunction3() {
    memPtr_ = &MyClass::fooBar;

...

And on the lines

memPtr_ = &MyClass::foo;

and

memPtr_ = &MyClass::bar;

and

memPtr_ = &MyClass::fooBar;

when I compile - I get the error:

"cannot convert 'MyClass& (MyClass::*)(ParamType)'
to MyClass* (MyClass::*)(ParamType)' in assignment."

I've searched - but I can't seem to find the solution to this problem - what is the correct syntax to assign a member function to the pointer to member function 'memPtr_'?

Upvotes: 1

Views: 94

Answers (2)

user1296259
user1296259

Reputation: 521

Jrok is correct, and I fixed the problem. I simply changed:

MyClass* (MyClass::*memPtr_) (ParamType);

to...

MyClass& (MyClass::*memPtr_) (ParamType);

Upvotes: 2

Paul Evans
Paul Evans

Reputation: 27567

You don't take the address of a function name with no (), that's the pointer.

Upvotes: 0

Related Questions