Sijith
Sijith

Reputation: 3940

Singleton class issue in Qt

i created a singleton class and trying to access that class in other class but getting error "cannot access private member"

Setupconfig is my singleton class and i am trying to access this class in other class which have QMainWindow

And here is the error message:

Error 'Setupconfig::Setupconfig' : cannot access private member declared in class 'Setupconfig'

Setupconfig.h
static Setupconfig *buiderObj()
{
    static Setupconfig *_setupObj= new Setupconfig();
    return _setupObj;
}

private:
Setupconfig();

//////////////////////////////////////
EasyBudget.h
class EasyBudget : public QMainWindow, public Ui::EasyBudgetClass, public Setupconfig
{
Q_OBJECT
public:
Setupconfig *setupObj;
}

//////////////////////////////////////
EasyBudget.cpp
EasyBudget::EasyBudget(QWidget *parent, Qt::WFlags flags)
: QMainWindow(parent,Qt::FramelessWindowHint)
 {
 setupObj=Setupconfig::buiderObj();
 }

Upvotes: 0

Views: 4640

Answers (4)

Appar
Appar

Reputation: 1

There are drawbacks in this approach, both copy constructor and assignment constructors (as generated by C++ compiler by default) will make a copy of the so called singleton class (here names: SetupConfig). You should also declare those tow constructors as private well.

Upvotes: 0

Jujjuru
Jujjuru

Reputation: 661

Why are you deriving "EasyBudget" from the singleton class "SetupConfig"?

Remove that part to resolve your problem.

EasyBudget.h
class EasyBudget : public QMainWindow, public Ui::EasyBudgetClass
{......

Upvotes: 0

David Dibben
David Dibben

Reputation: 18794

You should declare the static member in a source file not in a header file, whether or not you use the static class member or static function member approach. Your basic appoach should work, if the instance() function is a public member:

//setupconfig.h
class Setupconfig 
{
 public:  

static Setupconfig* instance();


private:
        SetupConfig();
};

//setupconfig.cpp
static Setupconfig* SetupConfig::instance()
{
   static Setupconfig* _setupObj= new Setupconfig();
   return _setupObj;
}

SetupConfig::SetupConfig()
{
    //....
}

Using the class member approach is also possible

//setupconfig.h
class Setupconfig 
{
 public:  

static Setupconfig* instance();


private:
        SetupConfig();

        static Setupconfig*  _setupObj;
};

//setupconfig.cpp
Setupconfig*  Setupconfig::_setupObj = 0;

static Setupconfig* SetupConfig::instance()
{
   if (_setupObj == 0) {
        _setupObj = new Setupconfig;
   }
   return _setupObj;
}

SetupConfig::SetupConfig()
{
    //....
}

Upvotes: 2

KhanS
KhanS

Reputation: 1195

Try This

 public:
    static Setupconfig *buiderObj() 
    { 
        if(*_setupObj; != null)
        {
           _setupObj= new Setupconfig(); 
        }
    return _setupObj; 

    } 
    public:
    Setupconfig(){}
    private:
    Setupconfig *_setupObj;

Upvotes: 0

Related Questions