Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't constructor be declared as static in c++?

I have recently finished reading the 1st Vol. of Thinking in C++ by Bruce Eckel and have now turned to applying the knowledge to some practical use.

I was recently working with static member functions and tried making the constructor static, for which the compiler was unhappy. I checked for the reason in the book but couldn't find any.

Can anyone explain why?

P.S.: After seeing some responses, I would like to mention that the confusion arises from my knowledge that C# (and Java) allows constructors to be declared as static.

like image 782
Sankalp Avatar asked Jul 06 '13 07:07

Sankalp


People also ask

Why static constructor is not allowed?

A constructor is called when an object of a class is created, so no use of the static constructor. Another thing is that if we will declare static constructor then we can not access/call the constructor from a subclass. Because we know static is allowed within a class but not by a subclass.

What happens if we declare constructor as static?

The user has no control on when the static constructor is executed in the program. A static constructor is called automatically. It initializes the class before the first instance is created or any static members declared in that class (not its base classes) are referenced.

Can we declare constructor static?

No, we cannot define a static constructor in Java, If we are trying to define a constructor with the static keyword a compile-time error will occur. In general, static means class level. A constructor will be used to assign initial values for the instance variables.

Why we Cannot declare constructor as final?

The child class inherits all the members of the superclass except the constructors. In other words, constructors cannot be inherited in Java therefore you cannot override constructors. So, writing final before constructors makes no sense. Therefore, java does not allow final keyword before a constructor.


1 Answers

The purpose of a constructor is to initialize the contents of an instance of the class.

Static methods don't have an instance associated with them.

Hence there is no such thing as a static constructor.

like image 124
NPE Avatar answered Oct 09 '22 07:10

NPE