When do we need a private constructor in C++?

Viewed 56912

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?

8 Answers

If you create a private constructor you need to create the object inside the class

#include<iostream>
//factory method
using namespace std;
class Test
{
 private:
 Test(){
 cout<<"Object created"<<endl;
}
public:
    static Test* m1(){
        Test *t = new Test();
        return t;
    }
    void m2(){
        cout<<"m2-Test"<<endl;
    }
};
int main(){
 Test *t = Test::m1();
 t->m2();
 return 0;
}

A private constructor in C++ can be used for restricting object creation of a constant structure. And you can define a similar constant in the same scope like enum:

struct MathConst{
    static const uint8 ANG_180 = 180;
    static const uint8 ANG_90  = 90;

    private:
        MathConst(); // Restricting object creation
};

Access it like MathConst::ANG_180.

Related