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?
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 ...
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.
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.
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() .
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);
You need the following funky syntax to call member functions through a pointer:
(this->*func)(foo, bar);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With