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 (*)()’

Recommended Answers

All 4 Replies

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.

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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.