c++visual-studiowinapihinstance

Initialize a reference to HINSTANCE inside constructor


I've a class and I want to make it as a global object(I have a good reason for it), but for that I need to initialize all the elements(If not I get C2512 No default constructor) which is a problem because I use a reference to an HINSTANCE on it that I need to initialize too and I don't know what can I do that. Here is the code:

class Foo {
private:
    //Class data
    HINSTANCE hInstance;
public:
    Foo(HINSTANCE & hInstance = ??, std::string name = "Default");
};

Foo foo;

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) {
    foo = Foo(hInstance, "SomeName");
}

Any Idea of how can I do that?, Thanks!


Solution

  • There is no reason to pass the HINSTANCE by reference if the constructor is not going to modify it, only store it. HINSTANCE is already a pointer to begin with, so just pass it by value and default it to NULL, eg:

    class Foo
    {
    private:
        //Class data
        HINSTANCE hInstance;
    public:
        Foo(HINSTANCE hInstance = NULL, const std::string &name = "Default");
    };
    
    Foo::Foo(HINSTANCE hInstance, const std::string &name)
        : hInstance(hInstance)
    {
        //...
    }
    

    Then you can do this:

    Foo foo;
    
    int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
    {
        foo = Foo(hInstance, "SomeName");
        //...
    }
    

    Alternatively:

    #include <memory>
    
    std::unique_ptr<Foo> foo; // or std::auto_ptr before C++11
    
    int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
    {
        foo.reset(new Foo(hInstance, "SomeName"));
    
        // or, in C++14 and later...
        // foo = std::make_unique<Foo>(hInstance, "SomeName");
    
        //...
    }