Private constructor in C++

An interview question asked will be "Can a constructor of a class be private".

Yes, it can be. By making a constructor as private, the program will compile fine. But the question is can we create objects from such a class. Of course not. How can we when we can not access the constructor?

But it is possible. We can create an object by having a static member function which creates an object by calling private constructor and return this object. 

 #include<iostream>  
 using namespace std;  
 class A  
 {  
  int m; 
  A(){cout<<"constructor";} //this is private constructor
  public:  
  static A createObject();  
  
 };  
 A A::createObject()  
 {  
  return A();  
 }  
 int main()  
 {  
    A obj1 = A::createObject();   
 }  


As we can see the function createObject() creates a temporary object using A() and returns this object.  

Since the method is static, it can be called without using any object. It is called using class name and scope resolution operator. 

Some time we not only want the constructor to be private, we want the class to let only one object created. Such a class is called singleton and has many applications. We will see how to create a singleton in a future post :)

 

Private destructor


This  is tricky. No matter how we create a constructor, destructor should be called and there is no way we can avoid this. Nor can we call a private a destructor. 

So even if we write a class with private destructor, we can NOT create an object from such a class. Because any object created must be destroyed which should call a destructor which is not possible.

Or should it be? What if we construct an object using dynamic memory allocation - using new. Then the object gets destroyed only if we call delete on that object. 

So we can have a private destructor for a class, and create an object from that class using new operator, if we do not call delete to destroy that object. 

 #include<iostream>  
 using namespace std;  
 class A  
 {  
  int m;  
  ~A(){}  
  public:  
  A(){}  
 };  
 int main()  
 {  
   A *ptr = new A;  
   cout<<"Hello world";  
 }  

As we see here, an object of A class is created using new A, but it is not destroyed using delete. The program compiles and runs fine.  Do not ask me what purpose does it serve. I don't know.

But next time some one asks you, can constructor or destructor of a class be private, impress them with a detailed answer.

 

Comments

Popular Posts