I'm trying to do something with pointers to function members that I cant' figure out how this works.
I have a class A that looks something like this
class A
{
public:
float Plus (float a, float b) { return a+b; }
float Minus (float a, float b) { return a-b; }
float Multiply(float a, float b) { return a*b; }
float Divide (float a, float b) { return a/b; }
};
I want to declare a pointer to A and then pass to another function a function pointer to one of the members of A.
Something likes this:
void Will_Get_Function_Pointer(float a, float b, float (A::*pt2Func)(float, float))
{
(...)
}
Where I would call it with something like this
A* myA = new A;
Will_Get_Function_Pointer(1.00,2.00, &myA->Minus)
I can't use static/const members because In my final implementation A will point to a specific A in a collection of A objects in something that will look like this
vector<A> vecA;
myA = &vecA[xxx]
Doing this fails miserably
typedef float (A::*pA)(float x, float y);
pA p = &myA->Minus;
and the compiler tells me to use &A::Minus but that wont work for me.
Can I even do this?
Cheers
Using a pointer-to-member-function to call a function Calling the member function on an object using a pointer-to-member-function result = (object. *pointer_name)(arguments); or calling with a pointer to the object result = (object_ptr->*pointer_name)(arguments);
You can use pointers to member functions in the same manner as pointers to functions.
Pass-by-pointer means to pass a pointer argument in the calling function to the corresponding formal parameter of the called function. The called function can modify the value of the variable to which the pointer argument points. When you use pass-by-pointer, a copy of the pointer is passed to the function.
The this pointer is a pointer accessible only within the nonstatic member functions of a class , struct , or union type. It points to the object for which the member function is called. Static member functions don't have a this pointer.
A* myA = new A;
Will_Get_Function_Pointer(1.00,2.00, &myA->Minus)
You cannot. You should use something like
void Will_Get_Function_Pointer(A* object, float a, float b,
float (A::*pt2Func)(float, float))
{
(object->*pt2Func)(a, b);
}
And calls it as
A* myA = new A;
Will_Get_Function_Pointer(myA, 1.00, 2.00, &A::Minus);
Simple example.
http://liveworkspace.org/code/79939893695e40f1761d81ba834c5d15
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