0

What is the use of private constructor in c++?

i studied about use of constructor in c++,generally it is declared in public section but we can also define it in private section... i can't understand the use of private constructor

30th Aug 2017, 6:31 AM
Ashish Negi
Ashish Negi - avatar
8 ответов
0
A private constructor does not allow to create more than one object at the same time.
30th Aug 2017, 11:18 AM
Ernaso Kerbizi
Ernaso Kerbizi - avatar
+ 9
I'm not really an expert on C++, so I can't translate it properly into code, but from what I understood during the course, it can be useful in class inheritance. Now, constructors are *not* inherited when deriving a class, but they are still *called* when you create an instance of a subclass. I can imagine that you can have more than one constructor for the main class, for example with different set of arguments. Let's assume that one of them is public and one is private. Now, if you derive a subclass from it, the subclass can only be instantiated using the superclass's public constructor and not the private one. So, in pseudo-code: class A() public constructor A(int x) private constructor A(int x,y) B inherit from A A(5) ==> that should be OK A(5, 8) ==> that should be OK B(5) ==> that should be OK B(5, 8) ==> that should not be possible
30th Aug 2017, 6:55 AM
Kuba Siekierzyński
Kuba Siekierzyński - avatar
+ 6
@Ernaso You're right, my bad, that's why I used pseudocode as I wasn't sure. In any way, is this supposed to prevent subclasses from accessing the superclass's private constructor?
30th Aug 2017, 11:50 AM
Kuba Siekierzyński
Kuba Siekierzyński - avatar
+ 1
dk se puch 😂😂😂😂😂
30th Aug 2017, 6:33 AM
Priyanka Khurana
Priyanka Khurana - avatar
+ 1
@Kuba A(5,8) it is not ok, you can not create an instance of a class through a private constructor. To create object you need to use static functions.
30th Aug 2017, 11:24 AM
Ernaso Kerbizi
Ernaso Kerbizi - avatar
+ 1
@Kuba Yes this is one of the reasons. Another one is to prevent the creation of more than one object simultaneously, since they are created through static functions.
30th Aug 2017, 12:52 PM
Ernaso Kerbizi
Ernaso Kerbizi - avatar
0
@Ernaso i know that but what are its practically applications...
31st Aug 2017, 6:48 AM
Ashish Negi
Ashish Negi - avatar