Class member function variable pointing to another member of the class function
Could you please explain to me why this code shows nothing but the last std :: cout line in main ()? Checked through similar threads on stackoverflow.com, couldn't connect them to mine, does this indicate at all? I'm trying to set a class function pointer to another class function:
#include <iostream>
class container;
class one {
public:
one()
{
eventsHandler = NULL;
};
~one() {};
void (container::*eventsHandler)();
};
class container {
public:
container()
{
zone = new one;
zone->eventsHandler = &container::events;
};
~container()
{
delete zone;
};
one *zone;
void events()
{
std::cout << "event handler is on..." << std::endl;
};
};
int main()
{
container *test = new container;
test->zone->eventsHandler;
std::cout << "just checker..." << std::endl;
delete test;
system("pause");
};
+3
source to share
3 answers
You need to provide an object to call the memeber function pointer:
container *test = new container;
(test->*test->zone->eventsHandler)();
Here test
is an object, test->zone->eventsHandler
is a pointer to the member function you saved, and operator->*
connects them.
Thus, it is very similar to any other member function; however, you can switch objects to call the element:
container *first = new container;
container *second = new container;
(first->*second->zone->eventsHandler)();
// both pointers point to the same function
std::cout << (first->zone->eventsHandler == second->zone->eventsHandler) << std::endl;
+1
source to share