Create Object of C++ Class with Private Constructor

When designing a C++ class, you can define the constructor to be private, public or even protected. In order to create object in the main function outside of the C++ class, you would need a way to call the constructor and allocate memory for the C++ Class which can be done using the new keyword. This post displays a way in which you can create object of a C++ class having private constructor as displayed below.

Create Object of Class with Private Constructor

Create Object of Class with Private Constructor

This way of creating objects of a C++ class with private constructor is called as factory method. Note that the object of the C++ class is actually created by a static function and is passed to the main function as a pointer to the object. Once the main function receives the pointer to the Object of the C++ Class, it can call any functions and use the object just like any other way. The given below code sample snipplet can be used to create your own C++ Project and play with the C++ code to learn static methods, pointers and more about C++ classes.

#include "stdafx.h"#include <iostream>class CPlusPlusClassWithPrivateConstructor{private:CPlusPlusClassWithPrivateConstructor(){std::cout << "Constructor of C++ Class with Private Constructorn";}public:static CPlusPlusClassWithPrivateConstructor* GiveMeClassObject(){return new CPlusPlusClassWithPrivateConstructor();}};int _tmain(int argc, _TCHAR* argv[]){CPlusPlusClassWithPrivateConstructor* pObjectOfClass;pObjectOfClass=CPlusPlusClassWithPrivateConstructor::GiveMeClassObject();delete pObjectOfClass;return 0;}

The above code compiles without any issues and the calling function is able to get a pointer to the object in a really easy and simple way. The output of this C++ project is as expected and whenever the object of this C++ class is created, the constructor gets called in to display confirmation message using the std::cout statement in the sample code.

Output of Class with Private Constructor Project

Output of Class with Private Constructor Project

The above output of this sample c++ project confirms that the object of the C++ class was created by the static function. Such static functions of C++ classes whose responsibility is to create objects are referred to as factory methods and can be useful in a complex C++ Object creation procedure.