dynamic_cast fails
-
There is an Edit control on the dialog. The ID is
IDC_EDIT
. InCMyDialog::OnInitDialog()
, I do this ...CEdit* pEdit = dynamic_cast<CEdit*>(GetDlgItem(IDC_EDIT) /* = some valid address */);
if(!pEdit) {
// Error;
}The
CWnd*
returned fromGetDlgItem
failed to convert to aCEdit*
. But isn'tCEdit
derived fromCWnd
? :confused:Maxwell Chen
-
There is an Edit control on the dialog. The ID is
IDC_EDIT
. InCMyDialog::OnInitDialog()
, I do this ...CEdit* pEdit = dynamic_cast<CEdit*>(GetDlgItem(IDC_EDIT) /* = some valid address */);
if(!pEdit) {
// Error;
}The
CWnd*
returned fromGetDlgItem
failed to convert to aCEdit*
. But isn'tCEdit
derived fromCWnd
? :confused:Maxwell Chen
Hi Maxwell,
Maxwell Chen wrote:
But isn't CEdit derived from CWnd
Yes, but GetDlgItem does not always return a CEdit pointer so the dynamic_cast runtime check fails. Have a look at the following document: Inside MFC: Handle Maps and Temporary Objects[^] Essentially... when GetDlgItem cannot find a permanent object in the MFC CHandleMap it will return a pointer to a CTempWnd object. So your code fails to dynamic_cast from CTempWnd to CEdit. As an experiment you should add a CEdit member variable to your class for IDC_EDIT. This will cause the CHandleMap to have a permanent handle. Now your code will magically work. :) Best Wishes, -David Delaune
-
Hi Maxwell,
Maxwell Chen wrote:
But isn't CEdit derived from CWnd
Yes, but GetDlgItem does not always return a CEdit pointer so the dynamic_cast runtime check fails. Have a look at the following document: Inside MFC: Handle Maps and Temporary Objects[^] Essentially... when GetDlgItem cannot find a permanent object in the MFC CHandleMap it will return a pointer to a CTempWnd object. So your code fails to dynamic_cast from CTempWnd to CEdit. As an experiment you should add a CEdit member variable to your class for IDC_EDIT. This will cause the CHandleMap to have a permanent handle. Now your code will magically work. :) Best Wishes, -David Delaune
Thank you! ;)
Maxwell Chen