I have a question about private constructors in C++. If the constructor is private, how can I create an instance of the class?
Should we have a getInstance() method inside the class?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
There are a few scenarios for having
privateconstructors:Restricting object creation for all but
friends; in this case all constructors have to beprivateRestricting certain type of constructor (i.e. copy constructor, default constructor). e.g.
std::fstreamdoesn’t allow copying by such inaccessible constructorTo have a common delegate constructor, which is not supposed to be exposed to the outer world:
For singleton patterns when the singleton
classis not inheritible (if it’s inheritible then use aprotectedconstructor)