A private constructor means that the user cannot directly instantiate the class. Instead, you can create objects using the Idiom Named Constructor , where you have static class functions that can create and return instances of the class.
The Named Constructor Idiom is for more intuitive use of the class. The example provided in the C ++ FAQ relates to a class that can be used to represent multiple coordinate systems.
This is pulled directly from the link. This is a class that represents points in different coordinate systems, but it can be used to represent both rectangular and polar coordinate points, so to make it more intuitive for the user to represent which coordinate system the returned Point returned, different functions are used.
There were many other answers that also corresponded to the spirit of why private constructors are ever used in C ++ (the Singleton pattern among them).
Another thing you can do with this: prevent the inheritance of your class , since derived classes will not be able to access your class, constructor. Of course, in this situation, you still need a function that instantiates the class.
birryree Jan 10 '11 at 15:52 2011-01-10 15:52
source share