+ 4
Why exactly must constructors be declared in public ?
I want to know the exact reason with explanation.
2 Respostas
0
Making them private doesnt make any sense because if they are private they can only be accesed within that class. That means you could use that constructor in a method of that class, but in order to use that method, the object has to be instantiated in some place of the program outside of the class, which is a contradiction.
This is wrong ----> But making them protected could make sense, because you may want to instantiate that class only in the derived classes.
EDIT:
Constructors cant be protected.
0
this->getName(): Making constructors private serves a purpose for C++ versions before C++11. The purpose is to prevent outside access to the constructor. This is required, if you need to hide the auto generated default constructor (if you don't want the class to be instantiated) or in the Singleton software design pattern where you want control over the instantiation of a class by the class itself. Put in short: Whenever you need control over the number of instantiations. Otherwise some other code can call your constructor and has therefore control over the number of instantiations of your class.
Protected constructors make sense for C++11 and after as you can call superclass constructors in these C++ versions. Not sure I've seen one, though.