+ 12
[CLOSED] Do constructors have to be public?
8 Answers
+ 25
@Tatari it's not necessary
constructors can also be private or default if u want
as @kai an @Jay said singleton is an exemple of constructors private.
+ 30
The public access modifier is accessible everywhere,
u can use it with : method, classes ,variable ,(constructors),packages...
+ 12
Example of singleton (factory pattern)
https://code.sololearn.com/cnLC3sFSFO20/?ref=app
+ 7
But do constructors HAVE TO be public?
+ 3
No they don't. If you create a singleton for example, the constructor even has to be private.
+ 1
Constructors don't have to be public, however there are not many cases where you'd want to have a private constructor. The singleton pattern is one of them, but I try to avoid singletons as much as possible.
An example of a private constructor I use rather often is a private copy constructor (together with a private assignment operator). Say you have class Foo, then you'd get:
private:
Foo(const Foo&) { /* do nothing */ };
Foo& operator= (const Foo&) { return *this; };
In this way people outside of your class cannot make a copy of your class. Thus if they want to pass an object of your class to a method they *must* pass a reference or pointer. This is really usefull if your class has lots of data or should be the only one in existence.
+ 1
Move to modern c++ standards is often easier said than done, especially when your company decides to stay with c++98...
0
Constuctors can be private and also static.
However, if you have class deriving from another class, the derived class cannot invoke the constructor from the base class since it's private.