Dave's Brain

Browse - programming tips - const member call non const member

Date: 2009sep29
Language: C++
Platform: 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 works in any C++ environment.
What this info useful to you? You can donate to say thanks

Add a comment

Sign in to add a comment
Copyright © 2008-2012, 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.