10

I am new to C++ and trying to understand the Singleton Pattern in C++.

myclass.h

#ifndef MYCLASS_H
#define MYCLASS_H

class Myclass {
    public:
        static Myclass* getInstance();

    private:
        Myclass(){}
        Myclass(Myclass const&){}
        Myclass& operator=(Myclass const&){}
        static Myclass* m_instance;
};

#endif // MYCLASS_H

myclass.cpp

#include "myclass.h"

Myclass* Myclass::getInstance() {
    if (!m_instance) {
        m_instance = new Myclass;
    }

    return m_instance;
}

The compiler can't compile. I get the following error, on all 3 lines with m_instance:

error: undefined reference to `Myclass::m_instance'

Niklas
  • 23,674
  • 33
  • 131
  • 170
  • Actually, there is a better way to implement Singleton. Check [this](https://stackoverflow.com/a/1008289/9783282). – Karlo Verde Apr 03 '19 at 05:02

1 Answers1

26

You forgot to add:

Myclass* Myclass::m_instance = 0; // or NULL, or nullptr in c++11

right under #include "myclass.h".

Borgleader
  • 15,826
  • 5
  • 46
  • 62