answersLogoWhite

0

Constructors are not declared public only. They can be declared protected and private, as required by the class. Protected constructors are only accessible to the class members and to derived classes. Private constructors are only accessible to the class members.

Although a default public constructor is required by the majority of classes, it is not true of all classes. Derived classes can call any public or protected base class constructor explicitly via their own construction initialisation sections.

Private construction is typically used in the singleton model to instantiate a private static instance of the class as and when it is required, whilst preventing multiple instances of the class from being created. However, class members also include friends of the class, thus external friend classes and friend functions can also instantiate objects via their private constructors.

Note that the whole point of public, protected and private access is not to hide information (as is often wrongly said) but in order to limit access to that information. The same applies to a class' constructors as it does to its member methods and member variables.

User Avatar

Wiki User

11y ago

Still curious? Ask our experts.

Chat with our AI personalities

EzraEzra
Faith is not about having all the answers, but learning to ask the right questions.
Chat with Ezra
SteveSteve
Knowledge is a journey, you know? We'll get there.
Chat with Steve
DevinDevin
I've poured enough drinks to know that people don't always want advice—they just want to talk.
Chat with Devin

Add your answer:

Earn +20 pts
Q: Why constructors are declared public only?
Write your answer...
Submit
Still have questions?
magnify glass
imp
Continue Learning about Engineering