c++structfunction-pointersmember-pointers

Assign the designated function to the function member pointer?


Given

void* hello () {
   cout << "Test.\n";          
}

and

struct _table_struct {
    void *(*hello) ();
};

How do we assign the function (hello) to the function member pointer?

I tried this (in main):

 _table_struct g_table;
 _table_struct *g_ptr_table = &g_table;

 // trying to get the struct member function pointer to point to the designated function
 (*(g_ptr_table)->hello) =  &hello; // this line does not work

 // trying to activate it
 (*(g_ptr_table)->hello)();

Solution

  • You don't dereference a pointer when assigning it to point to an object.

    g_ptr_table->hello = &hello; // note: the & is optional
    g_ptr_table->hello(); // dereferencing the function pointer is also optional