CPP/Classes/Singleton

From ProgrammingExamples
< CPP
Jump to: navigation, search

Singleton.h

class Log
{
  public:
    static Log& Instance(); //provide static member function to access the unique instance.
 
    double val;
 
  private:
    Log(){}; //prevent construction from outside this class' methods
    Log& operator=(const Log&); //prevent assignment
    Log(const Log&); //prevent copy construction
 
};

Singleton.cpp

Log& Log::Instance() {
  static Log instance; //create as a static object, i.e. will only be created once.
  return instance;
};

Main.cpp

#include <iostream>
#include "Singleton.h"
 
int main(int argc, char* argv[])
{
  Log::Instance().val = 2.0;
 
  std::cout << "val = " << Log::Instance().val << std::endl;;
 
  return 0;
};