Why can't constructor be declared as static in

2019-04-27 12:02发布

问题:

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.

回答1:

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.



回答2:

The language as such does not provide such functionality but it can be simulated indirectly. See this answer for more details. Not that I am really sure why you would ever need to do such a thing.



回答3:

The constructor member function constructs the object as specified, using an existing allocation -- i.e. this is present.

static member functions specify no storage to an object, so there is no associated instance to construct -- i.e. this is absent. Therefore, you cannot specify a static constructor.

Perhaps you are looking for a named static member function which returns an instance by value:

class t_object {
public:
  static t_object Func(…optional parameter list…) {
    t_object result(…ctor parameters…);
    …initialize result…
    return result;
  }
  ...
};


回答4:

One very useful feature of C++ over C is it provides a proper way for proper initialization and clean-up when the instances of a user defined type are created so that you have a well formed object ready to start working with.

The language achieves this through the mechanism of constructors and destructors.

As you might note that the reason why constructors and destructors exist are for maintaining the instances which are created.

Now static implies or at-least is used when there is something common which all the objects can use. You use it when there is really something which is to be shared among all the instances of the class which you create.

And the interface to the static data members of the class is provided through static member functions which are mainly used on the static data members.

So, if the constructor is allowed to be made static what should it possibly mean so that the definition given to it by making it static is still on the lines of the reason why it came into picture(to properly initialize the object before you get hold of it). So, if there is no object then it doesn't make sense to have a constructor/destructor.

If you think on the above lines it doesn't make any sense to allow constructors to be static at least in this case(in C++). Hence, it is not supported by this language.