Dave's Brain

Browse - Programming Tips - Is there a way for a class's const member function to call a non-const member?

Date: 2009sep29
Language: C++
Framework: MFC

Q.  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.

Add a comment

Sign in to add a comment
Copyright © 2008-2017, dave - Code samples on Dave's Brain is licensed under the Creative Commons Attribution 2.5 License. However other material, including English text has all rights reserved.