Firstly, I got this class:

class A{
    public:
        void show() {
            std::cout << "Hello World";
        }
} a;

I am trying to get the address of show() function.

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

    return 0;
}

And, it doesn't seem to work at all. Any idea?

Hmm, close.

>void (*ptr)();
Pointers to member functions have different syntax than pointers to functions. You need to specify the class:

void (A::*ptr)();

>ptr = &a.show;
Member functions aren't stored internally in objects. You need a class resolution for this:

ptr = &A::show;

>*ptr();
Non-static member functions require an object to run. Likewise, pointers to non-static member functions also require an object to act upon. There's a special syntax for that too:

(a.*ptr)();

Here's the whole thing:

#include <iostream>

class A{
public:
  void show() {
    std::cout << "Hello World";
  }
} a;

int main()
{
  void (A::*ptr)();
  ptr = &A::show;

  (a.*ptr)();

  return 0;
}

If show were a static member function, your code would work just fine after changing *ptr(); to (*ptr)(); or even ptr(); , as you don't have to dereference a function pointer to call the function.

It works interestingly.

EDIT : Narue has already answered.

I want to add just one more thing.

Member fucfions are not just stored by names internealy. Name of a member function of a class is would be Class::MemberFunction() not just MemberFunction() (unlike C).
It helps in function overloading when used with Name Mangling

-Prateek

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.