Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call member function through member function pointer? [duplicate]

Tags:

c++

I want to call member-functions through member-function-pointers. The calling function is also a member.

class A;

typedef int (A::*memFun)();

class A
{
    int P(){return 1;}
    int Q(){return 2;}
    int R(){return 3;}

    int Z(memFun f1, memFun f2)
    {
        return f1() + f2(); //HERE
    }
public: 
    int run();
};

int A::run()
{
    return Z(P, Q);
}

int main()
{
    A a;
    cout << a.run() << endl;
}

I am not doing it correctly, and am getting error-

main.cpp:15:19: error: must use '.*' or '->*' to call pointer-to-member function in 'f1 (...)', e.g. '(... ->* f1) (...)'
         return f1() + f2(); //HERE

Please show the correct way to do it.

EDIT - there is another error, which is solved by having-

return Z(&A::P, &A::Q);
like image 848
Vinayak Garg Avatar asked Apr 29 '13 10:04

Vinayak Garg


People also ask

Can we call member function using this pointer?

You can use pointers to member functions in the same manner as pointers to functions. You can compare pointers to member functions, assign values to them, and use them to call member functions.

How do you access member functions using pointers?

To access a member function by pointer, we have to declare a pointer to the object and initialize it (by creating the memory at runtime, yes! We can use new keyboard for this). The second step, use arrow operator -> to access the member function using the pointer to the object.

How do you call a function with a function pointer?

Calling a Function Through a Function Pointer in Cusing function pointer (a) int area = (*pointer)(length); // 3. using function pointer (b) int area = pointer(length);

How do you call a member function?

A member function is declared and defined in the class and called using the object of the class. A member function is declared in the class but defined outside the class and is called using the object of the class.


2 Answers

(this->*f1)() + (this->*f2)();

Regardless of whether you're calling it from inside the class, you have to explicitly specify the object on which to call (in this case this). Also note the required parentheses. The following is wrong:

this->*f1() + this->*f2()
like image 69
Armen Tsirunyan Avatar answered Sep 20 '22 17:09

Armen Tsirunyan


Like this:

(this->*f1)() + (this->*f2)()
like image 45
Kerrek SB Avatar answered Sep 17 '22 17:09

Kerrek SB