0

How can constructors be private?

22nd Sep 2018, 11:29 AM
Vaibhav
Vaibhav - avatar
4 Answers
+ 2
usually those are used for friend classes.
22nd Sep 2018, 12:14 PM
hinanawi
hinanawi - avatar
0
hinanawi please explain it further.
22nd Sep 2018, 12:15 PM
Vaibhav
Vaibhav - avatar
0
you make constructor private when you don't want it to be used to create the object from outside without control. so only a friend class or a public class method of that class can be used to create a new instance, and can do some checks first. Example: if you want to ensure there is only one instance of that class, you can have a class variable as a counter, and a class method "create" that calls the constructor and returns the object only if the counter is null;
22nd Sep 2018, 12:35 PM
ifl
ifl - avatar