MessageBox in const function
I wrote this simple const class method:
void CTest::MSGTest() const
{
MessageBox(_T("This is a simple test"));
}
This method has an error:
The object has type classifiers that are not compatible with the CTest :: MessageBoxW member function
I know this is because I am using const . A method can be a const method if the member variables do not change at runtime. I would like to know which MessageBox variables are being modified and how the modification manifests itself.
I think this is the m_hWnd handler, but I don't know.
source to share
The problem is not that neither your function nor MessageBox
any member variables are modifying - they are not there and it is easy to see.
The problem is that it is MessageBox
not marked as const
and so you have a member function const
(yours) calling non const
one ( MessageBox
). This is not resolved and that's the problem.
So why isn't it flagged const
? I doubt you will ever get a definitive answer to this question if one reason really exists.
Personally, I suspect it's a combination of factors that caused it not to be const
originally, and now it is.
One potential reason is that many of the internal MFC bits and parts of them involve manipulation and customization of maps - for example, maps that associate Windows HWND objects with MFC objects CWnd
.
They may have had to relax the use of const
non- const
function calls to account for calls deep in call chains in places that users never see.
So why not use it mutable
, maybe even const_cast
? Remember that MFC has been around for a long time, and when it was developed the Microsoft compiler might not support some of the more exotic C ++ features at the time.
source to share
In my opinion, if CTest
deduced from CWnd
(explicitly or not) - showing a dialog box in this object CWnd
means changing the state of the window / control. Suppose it is CTest
obtained from a CDialog
, and pressing some button calls this function ( CTest::MsgTest
). This effectively means that the state of the dialog has changed (from the user's point of view). It doesn't matter if a modal or modeless dialog is displayed - the state has changed, so the method shouldn't be const
.
source to share