Search code examples
c++windowswinapivectorhwnd

Vector and HWND Zero memory error c++


I wanted to create multiple windows ..So rather than writing them over and over again,I decided to use vector to keep list of all HWND and update them as programn proceeds.But Its doesnt seem to work as expected .. it is giving me a access violation error .

i tried initializing the vector.But nothing seems to work

WindoManager.h

  #include<windowsx.h>
#include<Windows.h>
#include<vector>
#include<list>
#include<iostream>
using namespace std;


class WindowManager{

    // Constructor
    WindowManager();

    // Destructor
    ~WindowManager();

private:
    vector<HWND> wnds;
    HWND hwnd;

public:
    void CreateNewWindow(HINSTANCE hinst,WNDCLASSEX * ex,HWND * Parent,HWND * ReturnWind,int Width,int Height,int X,int Y);
    void ShowWindows(int);
    int HandleMseeages();

};

WindowManager.cpp

#include"WindowManager.h"

WindowManager::WindowManager()
{


}

void WindowManager::CreateNewWindow(HINSTANCE hinst,WNDCLASSEX * ex,HWND * Parent,HWND * ReturnWind,int Width,int Height,int X,int Y)
{
    if(Parent == NULL)
    {
      hwnd = CreateWindowEx(NULL,ex->lpszClassName,ex->lpszMenuName,WS_OVERLAPPEDWINDOW,X,Y,Width,Height,NULL,NULL,hinst,NULL);
        wnds.push_back(hwnd);
        *ReturnWind = hwnd;
    }
}

void WindowManager::ShowWindows(int show)
{
    for(vector<HWND>::iterator it = wnds.begin();it != wnds.end() ; ++it)
    {
        ShowWindow(*it,show);
    }
}


int WindowManager::HandleMseeages()
{
    MSG msg;

 for(int i=0;i< wnds.size();++i)
    {
        if(PeekMessage(&msg,wnds[i],0,0,PM_REMOVE))
        {
            TranslateMessage(&msg);
            DispatchMessage(&msg);

            if(msg.message == WM_QUIT)
                return 0;
        }
    }

 return 1;
}

And the function gets called from source.cpp

....//Removed unwanted code

WindowManager * WndManager = {0};

    WndManager->CreateNewWindow(hinst,&classex,NULL,&hwnd,500,500,0,0);
    WndManager->ShowWindows(cmdshow);

i dont know whats wrong..Please do help me out

Thanks


Solution

  • The problem seems to be in this line:

    WindowManager * WndManager = {0};
    

    You are declaring a pointer without allocating an object and calling it's constructor.

    Allocate an object as:

    WindowManager * WndManager = new WindowManager;
    

    Or just simply define it in the stack and use the right calls (as suggested by Richard Hodges):

    WindowManager WndManager;
    
    WndManager.CreateNewWindow(hinst,&classex,NULL,&hwnd,500,500,0,0);
    WndManager.ShowWindows(cmdshow);