PeakGen
PeakGen

Reputation: 23035

Unable to implement Singleton Pattern

Please have a look at the following code

UIHandler.cpp

#include "UIHandler.h"
#include <iostream>

using namespace std;



UIHandler::UIHandler()
{

}


UIHandler::~UIHandler(void)
{
}

UIHandler *UIHandler::getInstance()
{
    if(uiHandler==NULL)
    {
        uiHandler = new UIHandler();
    }

    return uiHandler;
}

UIHandler.h

#pragma once
class UIHandler
{
public:

    ~UIHandler(void);


    static UIHandler *getInstance();

private:

    UIHandler *uiHandler();
    UIHandler();
};

I am new to C++ and I am trying to implement the singleton pattern here. But, this one is giving errors! It says "expression must be a modifiable lvalue", in the place uiHandler = new UIHandler();

Why is this? Please help!

Upvotes: 0

Views: 74

Answers (1)

Luchian Grigore
Luchian Grigore

Reputation: 258628

UIHandler *uiHandler(); declares uiHandler as a method, not a data member. Change it to

static UIHandler *uiHandler;

The static is there because you're accessing it from a static method.

Note that a better way would be

UIHandler& UIHandler::getInstance()
{
    static UIHandler uiHandler;
    return uiHandler;
}

and just get rid of the member.

Don't forget to disallow copying.

Upvotes: 3

Related Questions