Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a member function pointer within a class

Given an example class:

class Fred
{
public:
Fred() 
{
    func = &Fred::fa;
}

void run()
{
     int foo, bar;
     *func(foo,bar);
}

double fa(int x, int y);
double fb(int x, int y);

private:
double (Fred::*func)(int x, int y);
};

I get a compiler error at the line calling the member function through the pointer "*func(foo,bar)", saying: "term does not evaluate to a function taking 2 arguments". What am I doing wrong?

like image 982
neuviemeporte Avatar asked May 24 '10 16:05

neuviemeporte


People also ask

How do you pass a class member function as a function pointer?

If you need to access any non-static member of your class and you need to stick with function pointers, e.g., because the function is part of a C interface, your best option is to always pass a void* to your function taking function pointers and call your member through a forwarding function which obtains an object ...

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.

Can we define member function inside the class?

In addition, the function name in the definition must be qualified with its class name using the scope-resolution operator ( :: ). Although member functions can be defined either inside a class declaration or separately, no member functions can be added to a class after the class is defined.

How do you access a member function of a class?

Accessing data members and member functions: The data members and member functions of class can be accessed using the dot('. ') operator with the object. For example if the name of object is obj and you want to access the member function with the name printName() then you will have to write obj. printName() .


2 Answers

The syntax you need looks like:

((object).*(ptrToMember)) 

So your call would be:

((*this).*(func))(foo, bar);

I believe an alternate syntax would be:

(this->*func)(foo, bar);
like image 132
fbrereto Avatar answered Oct 13 '22 04:10

fbrereto


You need the following funky syntax to call member functions through a pointer:

(this->*func)(foo, bar);
like image 22
Thomas Avatar answered Oct 13 '22 04:10

Thomas