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
8 odpowiedzi
0
A private constructor does not allow to create more than one object at the same time.
+ 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
+ 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?
+ 1
dk se puch 😂😂😂😂😂
+ 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.
+ 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.
0
@Ernaso i know that but what are its practically applications...