Date: 2009sep29
Language: C++
Framework: MFC
Q. C/C++: Is there a way for a class's const member function to call a non-const member?
A. Usually this isn't allowed for good reason. If you want a member to call
a non-const member then make the caller non-const! But you already know that.
So here is how it can be done... use a const_cast on the "this" pointer:
void MyClass::MyConstMember() const
{
const_cast<CMyClass*>(this)->MyNonConstMember();
}
For example, the Windows CListCtrl member GetExtendedStyle() is non-const but since it doesn't change anything it should be const. In a wrapper class, called CMyListCtrl, I made a member called GetExtendedStyleConst() that is const and simply calls the non-const base class member:
DWORD CMyListCtrl::GetExtendedStyleConst() const
{
return const_cast<CMyListCtrl*>(this)->CListCtrl::GetExtendedStyle();
}
This technique is not restricted to Windows. It should work in any C++ environment.