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.
Chat with our AI personalities
You cannot. Constructors are specific to the class in which they are declared. They cannot be inherited and so they cannot be virtual.
This is not necessarily true. The only rules for this are that interface methods may not be private. They may be public, protected, or have the default (blank) access modifier.
You can have any number of constructors for a class. All we need to do is implement constructor overloading. Ex: let us say we want to create multiple constructor for a class Test Public class Test { Public Test() { //code } Public Test(int vals) { //code } Public Test(String val) { //code } }
Constructors have no value, zero or otherwise. That is, constructors cannot return a value. This is because constructors are not functions in the sense you cannot call a constructor directly. Constructors are invoked in the background when you instantiate an object of the class, thus any return value would be lost in the background, and would therefore not be visible to the invokee.
I dont think we can have Protected Constructors but yes we can have Private constructors. We can declare the constructor as Private to ensure that no other class can instantiate it. We use this in the singleton design pattern