I'm using C++ (not C++11). I need to make a pointer to a function inside a class. I try to do following:
void MyClass::buttonClickedEvent( int buttonId ) { // I need to have an access to all members of MyClass's class } void MyClass::setEvent() { void ( *func ) ( int ); func = buttonClickedEvent; // <-- Reference to non static member function must be called } setEvent();
But there's an error: "Reference to non static member function must be called". What should I do to make a pointer to a member of MyClass?
A non- static member function is a class / struct / union member function, which is called on a particular instance, and operates on said instance. Unlike static member functions, it cannot be called without specifying an instance. For information on classes, structures, and unions, please see the parent topic.
A class can have non-static member functions, which operate on individual instances of the class. class CL { public: void member_function() {} }; These functions are called on an instance of the class, like so: CL instance; instance.
A static member function can be called, even when a class is not instantiated. A static member function cannot have access to the this pointer of the class. A non-static member function can be declared as virtual but care must be taken not to declare a static member function as virtual.
A non-static member function is a function that is declared in a member specification of a class without a static or friend specifier. ( see static member functions and friend declaration for the effect of those keywords)
The problem is that buttonClickedEvent
is a member function and you need a pointer to member in order to invoke it.
Try this:
void (MyClass::*func)(int); func = &MyClass::buttonClickedEvent;
And then when you invoke it, you need an object of type MyClass
to do so, for example this
:
(this->*func)(<argument>);
http://www.codeguru.com/cpp/cpp/article.php/c17401/C-Tutorial-PointertoMember-Function.htm
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