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.
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With