Instantiate a singleton class i.e no more than one instance possible

This tip submitted by Anjan Ghose on 2013-06-30 21:50:51. It has been viewed 2724 times.
Rating of 0.0 with 0 votes

In header file, declare a class that contains a static pointer to itself, and a static declaration to return it. Initialize this to 0 in source file, and provide the static method to return the pointer. For example,

Class single {
  static single* selfptr;
  static single* instance();

single* single::selfptr = 0;
single* single::instance() {
  if (selfptr == 0) {
     selfptr = new single();
  return selfptr;

When instantiating in mainstream code, use the instance method i.e

single* myobjectptr;
myobjectptr = single::instance();

More tips

Help your fellow programmers! Add a tip!