I'm wondering if I haven't fully understood C++ casts versus old C-Style cast. In MFC I have this method:
CWnd * GetDlgItem(UINT uResId);
I'm expecting that a CComboBox (or CEdit), which is derived from CWnd, requires this kind of cast:
dynamic_cast<CComboBox *>(GetDlgItem(IDC_COMBO1));
// for CEdit:
dynamic_cast<CEdit *>(GetDlgItem(IDC_EDIT1));
but this operation causes a crash for using null pointer, that means that cast have failed. Using:
reinterpret_cast<CComboBox *>(GetDlgItem(IDC_COMBO1));
// for CEdit:
reinterpret_cast<CEdit *>(GetDlgItem(IDC_EDIT1));
fixes the problem, but I'm disappointed. What am I missing?
The problem is that GetDlgItem
may return a temporary CWnd*
pointer.
If the window is a CWnd
derived class and the window is created with CWnd::Create(Ex)
or the window is subclassed, RTTI will work.
When the window is created by Windows (due to a dialog template) and the Window isn't subclassed by the MFC (with DDX_Control
ow CWnd::SubclassWindow
), GetDlgItem
just returns a temporary CWnd*
, with CWnd::FromHandle
. This window handle is always of the base type CWnd
.
If you want to check if this window is really a Edit
control you can use CWnd::GetClassName
. Casting to a CEdit*
is safe and convenient because a CEdit
control communicates with it's HWND
counterpart just via Window messages. So this works for all basic integrated window classes.
I'm wondering if I haven't fully understood C++ casts versus old C-Style cast. In MFC I have this method:
Probably you do understand the difference well, but MFC had been released before the RTTI in the C++ standard, having its own support for RTTI, which doesn't meet the standard way.
So alternatively, you could use DYNAMIC_DOWNCAST
instead as follows:
DYNAMIC_DOWNCAST(CEdit, GetDlgItem(IDC_EDIT1));
The common practice for this, however, is not to cast, but to create a member variable that represents your MFC control, using DDX_Control, which you can easily accomplish by doing Right Click, and selecting Add Variable... or through MFC Class Wizard.
EDIT
So I misunderstood an essential part of the OP's question about when the crash occurs. The crash is because of dereferencing nullptr
, the valid result of dynamic_cast
, not the dynamic_cast
itself.
@xMRi answers why it crashes in detail.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With