I wanted my class to only have one object created at any given time?
I want to limit the amount of object which can be created from a particular class , It should only have one or zero object at any give moment , I have tried a way and it seems to work
Please check it out and tell me some improvements I maybe will be able to make
That is fine, but you can make it easier.
Just type in the constructor some int variable equal to- 0 that everytime time you create object from this class he will be raise by 1, then, put a if statement in the same constructor that if the int variable is higher then 1 you will call the distractor.
There is a standard design pattern known as a singleton which restricts the creation of an object to a single instance. See...
The reason programmers read about design patterns, data structures and algorithms is so that we don't have to keep on reinventing the wheel.
There's certainly no need to be adding integers to the constructor. The singleton design pattern usually uses a static variable to track the existence of the object.
Unnecessary construction, destruction and object count tracking going on. You need at the max 1 object of your class.
make ptr a static member and initialize it to nullptr
Then in getInstance
if (ptr == nullptr)
create instance and make ptr point to it
ptr = new Manager()
return ptr; (no need for else)
next call to getInstance will check if (ptr == nullptr) // which will not be the case
so return already existing ptr.