Showing posts with label CWnd. Show all posts
Showing posts with label CWnd. Show all posts

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....


Monday, May 28, 2007

MFC Temporary Handles

If we want a CWnd object from  a hwnd , the first functions coming to my mind is these.
CWnd -> Attach()
or
CWnd::FromHandle().


The difference is this , the CWnd::FromHandle first checks if the specified hwnd is already in the Permenent handle map. If so it
returns the CWnd * from the map. If it can't find it searches in the Temporary map and returns. if it couldn't see the hwnd in both
permenent and temporary map it will create a new CWnd * object and add it to temporary map.


So the point is this. The temporary objects are deleted during the idle time. So don't store the pointer returned from CWnd::FromHandle like functions ( CPen, CDC , CGDIObject etc ).


If we are calling Attach. it should be detached, otherwise during the destruction of the class (CWnd), the destructor calls the ::DestroyWindow API , to destroy the attached window( may be we don't want to do that). Also don't give non-MFC window pointer to Attach function. It is not valid . If you want , then use FromHandle function