C++’s “pointer-to-member” operator

Lessons learned today: There are still operators in C++ I did not know 🙂

I was suprised when I saw these strange operators ->* and .*.

You can use those operators when you have a pointer to a member function. In order to call this function, you need an explicit instance. ->* and .* combines function pointer and instance. .* is a built-in operator and cannot be overloaded. ->* may be overloaded.

class A
   void f() {}
   void g() {}


void (A::*ptr)(); // This is a pointer to a member function of A

// Let the pointer point to f
ptr = &A::f;
// We cannot use this pointer without an object
A a;
(a.*ptr)() // Call f on instance a
// Now we have a pointer to an instance
A *b = new A;
(b->*ptr)() // Call f on instance b

More on this

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.