Thursday, June 7, 2007

Non-Polymorphic class And dynamic_cast

dynamic_cast, Non_polymorphic class , Some mfc thoughts
----------------------------------------------------------------------------------------

dynamic_cast couldn't be applied to "non-polymorphic" class . So what is this "non-polymorphic" class ? A class which has no virtual function is caled the non_polymorphic class. If you try to use dynamic_cast with non-polymorphic class. the result will be compile error. For example the code written below cause to an error.

class SuperBase
{
};
class Derived : public SuperBase
{
};


Derived* pDer = new Derived;
SuperBase* pBase = pDer;
Derived* pTest = dynamic_cast<Derived*>(pBase);

This code will try to cast pBase to Derived* , but it will not compile. To correct it use static_cast.

Derived* pTest = static_cast<Derived*>(pBase);

See the code below
CWnd *pWnd = GetDlgItem(IDC_BUTTON1); // IDC_BUTTON1 is a windows button control in a dialog.

Try to cast this pWnd to CButton* with dynamic_cast will give you a null pointer, like dynamic_cast<CButton*>(pWnd) will give you a null pointer. Means the cast is not working . Why ?????

Because mfc is creating some temporary objects inside , to reduce overehad. I will try to explain this later....


No comments: