Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Home » Tip Bank » C++
Language: C++
Expertise: Advanced
Jun 25, 2001



Building the Right Environment to Support AI, Machine Learning and Deep Learning

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
 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
Danny Kalev
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date