0

I am using QNX momemtics IDE 5.0.1 with a virtual machine VmPlayer to run QNX Client. I am using singleton pattern for a class. When calling the instance of the class I am getting the error "Undefined reference to "error: 'constexpr' needed for in-class initialization of static data member 'DemoClass* DemoClass::s_instance' of non-integral type [-fpermissive]". The code snippet is as below:

class DemoClass
{
   static DemoClass*s_instance = nullptr;
   public :
        DemoClass();
    virtual ~DemoClass();

    //singleton 
    static DemoClass* GetInstance()
    {
        if (!s_instance)
          s_instance = new DemoClass;
        return s_instance;
    }

}

I am calling the getter function in another class as below:

class AppMgr
{
DemoClass* m_demo;

public:
    AppMgr();
    virtual ~AppMgr();
    void Load();
);

void AppMgr::Load()
{
   m_demo = = DemoClass::GetInstance();
}

I added the definition of the static member still facing the error. Please suggest.

apb_developer
  • 321
  • 2
  • 9

2 Answers2

2

Beside few syntax errors which make the sample not working, you need to declare s_instance outside of the class since it's static:

class DemoClass
{
    static DemoClass* s_instance;

public :
    DemoClass();
    virtual ~DemoClass();

    //singleton 
    static DemoClass* GetInstance()
    {
        if (!s_instance)
        s_instance = new DemoClass;
        return s_instance;
    }

};

DemoClass* DemoClass::s_instance = nullptr;

This fixes the mentioned error, and there are more to fix like m_demo = = DemoClass::GetInstance();, constructor/destructor definition, etc.

karastojko
  • 1,156
  • 9
  • 14
1

If you have a static field in a class, you can only in-place initialize it if it const of integral type or it is a constexpr. s_instance is neither, so you need to separate the declaration and definition. You need to define s_instance outside the scope of the class, in one of your C++ files, e.g.:

DemoClass.h:

class DemoClass
{
    static DemoClass* s_instance;
}

DemoClass.C:

DemoClass *DemoClass::s_instance = nullptr;
Jakub Zaverka
  • 8,816
  • 3
  • 32
  • 48