Private constructor | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Private constructor

In which situation we can make constructor as private(with example)?

28th Aug 2016, 11:26 AM
Sreeni
Sreeni  - avatar
1 Answer
0
Private constructor means a user can not directly instantiate a class. Instead, you can create objects using something like the Named constructor idiom, where you havestatic class functions that can create and return instances of a class. The Named Constructor Idiom is for more intuitive usage of a class. The example provided at the C++ FAQ is for a class that can be used to represent multiple coordinate systems. This is pulled directly from the link. It is a class representing points in different coordinate systems, but it can used to represent both Rectangular and Polar coordinate points, so to make it more intuitive for the user, different functions are used to represent what coordinate system the returned Point represents. #include <cmath> // To get std::sin() and std::cos() class Point { public: static Point rectangular(float x, float y); // Rectangular coord's static Point polar(float radius, float angle); // Polar coordinates // These static methods are the so-called "named constructors" private: Point(float x, float y); // Rectangular coordinates float x_, y_; }; inline Point::Point(float x, float y) : x_(x), y_(y) { } inline Point Point::rectangular(float x, float y) { return Point(x, y); } inline Point Point::polar(float radius, float angle) { return Point(radius*std::cos(angle), radius*std::sin(angle)); } There have been a lot of other responses that also fit the spirit of why private constructors are ever used in C++ (Singleton pattern among them). Another thing you can do with it is to prevent inheritance of your class , since derived classes won't be able to access your class' constructor. Of course, in this situation you still need a function that creates instances of the class.
28th Aug 2016, 5:07 PM
Sunny Balani
Sunny Balani - avatar