C++ preventing user from creating object instances

384 views Asked by At

I have to create simple singleton object factory for some types of objects. The problem is that I can't find smart way to prevent user from creating object instances by constructors. I know that I can move constructors to private/protected section but how will the factory create new objects now when constructors are private/protected? Making factory a friend of every class isn't really smart as I need to predeclare factory in every header and write aditional "friend Factory;" in every class. How to do this correct?

1

There are 1 answers

0
Attersson On

In the class, add a static member as pointer to the same type of the class. This will be your singleton.

When initializing an instance, the constructor is ran.

If this is the first time, the static member is null (never initialized), run the constructor normally and set default values. In the end also set the static member to this. Now your singleton is initialized.

In subsequent constructor calls, the static pointer will not be null. Make a temporary pointer to the class type. Set this pointer to this, then set this to the static member and delete the pointer. This will delete the new instance and return the same static instance instead, everytime.