I want to declare an ordinary pointer (not a member pointer) to a member function. I have tried but apparently I am getting errors. Is this allowed in C++? Why is it not?

#include<iostream>

class A{
private: 
int m;

public:
void show(void){

std::cout<<"M= "<<m<<std::endl;

}





};


int main()
{
A a;
void (*ptr)(void);
ptr = a.show;
*ptr;


return 0;
}

The error I am getting is: argument of type ‘void (A::)()’ does not match ‘void (*)()’

Edited 1 Year Ago by anumash

You can't get a non-member pointer to a member function. If you did, and called it, what would the function use for this?

A pointer to member function still has to be invoked with an object of the appropriate type. You might be able to declare the pointer like this: void (A.*ptr)(void); A.ptr = a.show; but I'm not 100% certain of that. In any case, this would be, IMHO, really crappy code. It violates the KISS principal in so many ways!

Memeber functions are members of a class. Because of that they are not the same as free functions when it comes to function pointers.

void (*ptr)(void);

Will match any function that returns void at takes no parameters that is not a memeber function.

void (A::*ptr)(void)

Will match any function that returns void and takes no parmeters that is a memeber of A.

The reason for this is

void show(void)

Actually has a hidden parameter in it as non static class memeber functions take in the this pointer from the instance that calls it.

Edited 1 Year Ago by NathanOliver

Thank you for your replies @gusano79, @rubberman & @NathanOliver!

This article has been dead for over six months. Start a new discussion instead.