0

I'm learning about Singleton design pattern. I have the following code example:

//singleton.hpp
#ifndef SINGLETON_HPP
#define SINGLETON_HPP

class Singleton {
public:
    static Singleton& Instance();
private:
    Singleton();
    static Singleton* instance_;
};

#endif

and:

//singleton.cpp
#include "singleton.hpp"

Singleton* Singleton::instance_ = 0;

Singleton& Singleton::Instance() {
    if (instance_ == 0) {
        instance_ = new Singleton();
    }
    return *instance_;
}

Singleton::Singleton() {

}

What I don't understand is the line:

Singleton* Singleton::instance_ = 0;

What does this line do and how? I have never seen something like this.

darxsys
  • 1,420
  • 3
  • 19
  • 32

2 Answers2

0

that is the same as

Singleton* Singleton::instance_ = NULL;

It's just setting the instance to null at the beginning, so that the first time you grab the Singleton it will new up the Singleton object.

Then from there on out, anytime you try to get the Singleton it will give you the first instantiated object.

Kyle C
  • 1,547
  • 10
  • 23
0
Singleton* Singleton::instance_ = 0; 

just means

Singleton* Singleton::instance_ = NULL; 

Because it is static variable, you need to declare it in .h file and define it in .cpp file

Gisway
  • 5,314
  • 5
  • 33
  • 58
  • Oh, I didn't really check up on static variables enough. That's the answer I'm looking for. Thanks. – darxsys May 10 '13 at 21:17