Design Singleton class in C++ with example – Simple Steps

(Last Updated On: February 25, 2019)

Answer: Singleton class in C++ is the class that is designed to provide only one unique instance across the system. So, whenever we create c++ singleton instance, it will return the same instance created earlier if any.

About method and variables for Designing Singleton class in C++

Singleton class requires below methods and variables.

  1. Private singleton constructor and copy Constructor : Singleton class should not allow users to create singleton instances but they should request class to return an instance. Hence, make the constructor and copy constructor of singleton class private to prevent object instantiation.
  2. A public static function: As, it has blocked users to create objects, there should be a static function that returns object to the users using class name.
  3. A private static pointer: We need a static class pointer in singleton class to allocate object that will be returned to users. Why static pointer, as static function accepts only static variables as a parameter.

Design of C++ singleton class

[Just to focus, GetInstance() is a static method that will return class object pointer to users.

static Singleton* s_instance a private static pointer.]

C++ singleton class example

 

Singleton class example test:

 

Output :
Singleton class!!!
Address of object is:00757948
Singleton class!!!
Address of object is:00757948

Note that in the above output addresses of the objects are same.

NOTES:

Singleton is not a keyword, it is just the concept we apply over a class that need to return only one instance.

We have make copy constructor in singleton class private, as below code will violate singleton class design, if it is public and even though constructor is private.

//Checking copy constructor

 

      /*Singleton s_obj3 = *s_obj2;//derefrence the object to copy

      s_obj3.display();

      cout<<“Address of object is:”<<&s_obj3<<“\n”;*/

 

NOTE:
In the above single class design C++ singleton thread safe and C++ delete singleton object has been excluded. As for this singleton class interview question, interviewers expect only concept. However, they may ask for thread safe singleton class in C++ and object deletion design as a next questions or in some interviews, it may be a direct question.