+ 12

[CLOSED] Do constructors have to be public?

7th Mar 2018, 9:41 AM
luʁi
8 ответов
+ 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.
7th Mar 2018, 11:25 AM
Youssef Ouamou
Youssef Ouamou - avatar
+ 30
The public access modifier is accessible everywhere, u can use it with : method, classes ,variable ,(constructors),packages...
7th Mar 2018, 10:04 AM
Youssef Ouamou
Youssef Ouamou - avatar
+ 12
Example of singleton (factory pattern) https://code.sololearn.com/cnLC3sFSFO20/?ref=app
7th Mar 2018, 10:37 AM
jay
jay - avatar
+ 7
But do constructors HAVE TO be public?
7th Mar 2018, 10:11 AM
luʁi
+ 3
No they don't. If you create a singleton for example, the constructor even has to be private.
7th Mar 2018, 10:21 AM
Kai Schlegel
Kai Schlegel - avatar
+ 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.
7th Mar 2018, 9:28 PM
Freddy
+ 1
Move to modern c++ standards is often easier said than done, especially when your company decides to stay with c++98...
8th Mar 2018, 5:21 PM
Freddy
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.
7th Mar 2018, 11:37 AM
Prudhvi Vemulapalli
Prudhvi Vemulapalli - avatar