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;}};

size=3>
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

size=3>
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

size=3>

devx-admin

Share the Post: