user99545
user99545

Reputation: 1173

Initializing a static data member (class) within a class C++

I am trying to declare a static class within a parent class and initialize it, but I seem to be getting all sorts of errors.

/* MainWindow.h */
    class MainWindow
    {
        private:
        static DWORD WINAPI threadproc(void* param);
        static MainWindow *hWin;
    };
/* MainWindow.cpp */
#include "MainWindow.h"
      void MainWindow::on_pushButton_clicked()
        {
            HANDLE hThread = CreateThread(NULL, NULL, threadproc, (void*) this, NULL, NULL);
            WaitForSingleObject(hThread, INFINITE);
            CloseHandle(hThread);
        }

        DWORD WINAPI MainWindow::threadproc(void* param)
        {
            hWin = (MainWindow*) param;
            //Be able to access stuff like hWin->run();
            return 0;
        }

I have tried using MainWindow::hWin = (MainWindow*) param; and MainWindow::hWin = new MainWindow((MainWindow*) param)); and many others, but none seem to work. What is the proper way to do this? Are there any resources anybody would recommend on this subject, I have been tangling with class problems for a few days now and am very frustrated.

Upvotes: 1

Views: 613

Answers (2)

Paul Groke
Paul Groke

Reputation: 6447

Using a static variable like in your example will not allow you to have more than one instance, so it's best to avoid it if possible. And in your example there is no need to use one, you can easily use a local variable instead.

Just remove the static MainWindow *hWin; from your class definition, and modify MainWindow::threadproc() to use a local variable:

    DWORD WINAPI MainWindow::threadproc(void* param)
    {
        MainWindow* const hWin = static_cast<MainWindow*>(param);
        //hWin->whatever();
        return 0;
    }

However, if you really want to/have to use a static variable (for reasons that are not apparent in your example), then I'd suggest to set it in MainWindow's ctor - and just there. No need to explicitly pass it to the thread.

    MainWindow::MainWindow()
    {
        assert(hWin == 0);
        hWin = this;
    }

    MainWindow::~MainWindow()
    {
        assert(hWin == this);
        hWin = 0;
    }

    void MainWindow::on_pushButton_clicked()
    {
        HANDLE hThread = CreateThread(0, 0, threadproc, 0, 0, 0);
        WaitForSingleObject(hThread, INFINITE);
        CloseHandle(hThread);
    }

    DWORD WINAPI MainWindow::threadproc(void*)
    {
        // just use hWin, it already points to the one and only MainWindow instance
        return 0;
    }

Upvotes: 0

soulmerge
soulmerge

Reputation: 75714

Static members always consist of a declaration and a definition, you lack the definition in your cpp file. Put the following line outside of any functions:

MainWindow* MainWindow::hWin;

You can read more here or here.

Upvotes: 4

Related Questions