A singleton class

A singleton is a design pattern to ensure that one instance only of a class is created. An example of a singleton class is presented in order to explain the design.

class A
{
  public:
    A& instance();
    int aMethod();
  private:
    A();
};

As the constructor A() is declared private it is impossible to create a new instance of the class A by a new-statement. Instead, the only way to access the instance of A is through the method instance. A call of the method aMethod() will be indirect as shown in the statement

 ...
 int anInt = A::instance().aMethod();
 ...

The implementation of the method instance()in the singleton class is

A&
A::instance()
{
  static A myInstance;
  return myInstance;
}

The only existing instance of the singleton class is the static variable myInstance declared in the method instance(). This solution ensures that the the constructor of the class will be executed once only the first time the method A::instance() is referenced. All subsequent references to the instance() will return the internal static reference.