I had this problem some time ago and I gave up but lately it returned.
#include <iostream>
class element2D;
class node2D
{
public:
void (element2D::*FunctionPtr)();
void otherMethod()
{ std::cout << "hello" << std::endl;
((this)->*(this->FunctionPtr))(); //ERROR<-------------------
}
};
class element2D
{
public:
node2D myNode;
void doSomething(){ std::cout << "do something" << std::endl; }
};
int main()
{
element2D myElement;
myElement.myNode.FunctionPtr = &element2D::doSomething; //OK
((myElement).*(myElement.myNode.FunctionPtr))(); //OK
return 0;
}
I'm getting error at marked line:
pointer to member type 'void (element2D::)()' incompatible with object type 'node2D'
I would be really thankful for help. There was similar question today which partially helped me: link. But it doesn't seem to be the full answer to my problem.
Actually these two problems have only one difference - point where the function is called.
Thanks for your time
Calling a function using a pointer is similar to calling a function in the usual way using the name of the function. int length = 5; // Different ways to call the function // 1. using function name int area = areaSquare(length); // 2. using function pointer (a) int area = (*pointer)(length); // 3.
The call by pointer method of passing arguments to a function copies the address of an argument into the formal parameter. Inside the function, the address is used to access the actual argument used in the call. This means that changes made to the parameter affect the passed argument.
Function pointer to member function in C++ In C++ , function pointers when dealing with member functions of classes or structs, it is invoked using an object pointer or a this call. We can only call members of that class (or derivatives) using a pointer of that type as they are type safe.
It is true that a pointer of one class can point to other class, but classes must be a base and derived class, then it is possible.
"this" is a pointer to node2D but FunctionPtr refers to a member of element2D -- that is the error.
#if 0 // broken version
void otherMethod()
{ std::cout << "hello" << std::endl;
((this)->*(this->FunctionPtr))(); //ERROR<-------------------
}
#else // fixed version
void otherMethod( element2D * that )
{ std::cout << "hello" << std::endl;
((that)->*(this->FunctionPtr))();
}
#endif
Then you call it with something like:
myElement.myNode.otherMethod( &myElement );
There are things you could do to improve on this, but this should get you started.
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