Take the 2-minute tour ×

I defined a class that I want to use for building a window. One of the fields is hWnd and when the member function create() is called the HWND to the created window is stored there. I overloaded the (HWND) cast to return that value:

operator HWND() { return(hWnd); }

My program started crashing when I attempted to create child windows to the first, main window I created and I tracked it down to an odd value being returned by the typecast. I defined a typical getter function, getHwnd(), that works fine but the typecast just returns trash. Is there something that I'm missing?

The class definition:

class WindowBuilder
    WindowBuilder(FullWindow &fullWindow);
    operator HWND()                               { return(hWnd); }
    void SetCaption(char const * caption)         { windowName = caption; }
    void SetMenu(int resourceId);
    void SetRender(RECT rect, HWND parent);
    void SetButton(HWND parent);
    void Create();
    void Show(int nCmdShow = SW_SHOWNORMAL);
    HWND getHwnd ()                               { return(hWnd); }

    FullWindow &        window;
    HWND            hWnd;
    char const *        windowName;
    DWORD           style;
    int         x;
    int         y;
    int         width;
    int         height;
    HWND            hWndParent;
    HMENU           hMenu;
    void *          data;

Example of calling:

FullWindow renderWindowClass("STATIC", GlobalInstance, WndProc);
renderWindow = new WindowBuilder(renderWindowClass);
renderWindow->SetRender(rect,mainWindow->getHwnd());    // used to be (HWND)mainWindow 

/*RenderWindow = ::CreateWindow("STATIC", NULL, WS_CHILD | WS_VISIBLE | WS_BORDER,
    rect.bottom - rect.top, Window, NULL, hInstance, NULL);*/
share|improve this question
Can't tell without seeing more code. –  Ben Voigt Mar 19 '11 at 5:33
added the class declaration and one example of how I was using it. If you need more just ask. –  Matt Mar 19 '11 at 16:51

1 Answer 1

up vote 1 down vote accepted

You don't show the definition of mainWindow, but based on your use of ->, I would assume that it is a pointer to a WindowBuilder. So when you do (HWND)mainWindow, you are casting the pointer value to an HWND rather than invoking your cast operator. To invoke your cast operator, you would need to do something like (HWND)(*mainWindow).

Having said that, I feel obliged to say that you would have a cleaner design if you do not use cast overloads in this way. They can lead to subtle bugs due to automatic casts that can be hard to spot in the code. Using an explicit getHwnd() member is much more clear and reliable.

share|improve this answer
Thank you! That was exactly the problem. Thank you also for the other advice. This program is really just a learning project for me than a serious project so I was exploring things I hadn't done before. –  Matt Mar 19 '11 at 17:06

Your Answer


