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 have to use operator->*

to call the member function pointer and assign test

as the object to be called,

(test->*test->zone->eventsHandler)();

      

or more clearly



(test->*(test->zone->eventsHandler))();

      

LIVE

+3


source


You must call the function pointer on line 38 like this:



(test->*test->zone->eventsHandler)();

      

+1


source


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







All Articles