devxlogo

Pointers to const Member Functions

Pointers to const Member Functions

The const-ness of a member function is an integral part of its type. The following class defines two member functions, f(), g(), which have the same return type and parameter list:

 class A{public: int f(int n) { return 0;} int g(int n) const {return 0;}};


However, g() is a const member function, whereas f() isn’t. Therefore, their types are not the same:

 int (A::*pmf)(int)=&A::f;int (A::*pcmf) (int)const=&A::g; // ptr to const member


You can use pcmf to call a member function of a const object. Trying to use pmf in this context will fail because it’s not pointing to a const member function:

 const A *p=new A; // p is a pointer to a const object(p->*pcmf)(5); // fine, using ptr to const member(p->*pmf)(5); // error, not a pointer to a const member

See also  5 Tips to Manage a Remote Workforce
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist