nathan@orstcs.UUCP (nathan) (04/06/86)
Regarding: Re: initializing static members >> With the restriction that no initializer may be provided for the field >> ... and that no constructor may be provided for the class containing it, >> the problem begins to look interesting. >You've misinterpreted the C++ book. Section 8.5.1 in the reference >manual says , "No initializer can be specified for a static member, >and it cannot be of a class with a constructor." I'm in good company. The book is not exactly a model of clarity on this point. I reread the sentence for 10 minutes to figure out what the "it" referred to; maybe I'm stupid. It finally dawned that "it", the static member, may itself be an object of a class, and *that* class can't have constructors. > The reason for this restriction should be clear: when would the > constructor for the static member be called? The beginning of execution > would make sense ... but that may be a bit much to ask of the compiler. I think not. The compiler handles all the other pre-main initializations just fine. This really is no different. The problem is syntactic: declarations with initializers don't "fit", just as consts don't. > ... one can initialize it without reference to any instance of the class > using the class1::static_member syntax. Oh? And where must this initialization appear? In the initialization code for some *other* object, that's where. It seems there really is no way to avoid something like this: // in bleah.h class bleah { static int here; friend class bleah_hack; // have to mess up the declaration. public: int Here() { return 100; } } // in bleah.c class bleah_hack { bleah_hack() { bleah::here = bleah::Here(); }} b; ... >> The member function Here() is pretending to be a >> constant field, but it's not even a constant *expression* ... >...it behaves almost like a constant ... That's what I *said*. Look what happens to code like this: int bl_vec[bleah::Here()]; // illegal static int bl_h = bleah::Here(); // illegal void bleah::f(int h = bleah::Here()) { ... } // illegal Need I go on? >> By the way, 'b' defaults to static, not extern; see r8.1. >This last remark leads me to believe that you have out of date >documentation. ... I have pencilled in all of bs's corrections from the second edition of the book. Are there additional language specifications elsewhere? With strong type-checking, there's little reason *not* to make globals default to static. I would call it a feature. I suspect Dr. Stroustrup is beginning to regret allowing statics in classes, with all the worm-cans opening. Perhaps an official word on this subject (future handling of statics and consts in classes) would be forthcoming from the Architect himself. > Bill Hopkins ... ihnp4!druny!weh Nathan C. Myers orstcs!nathan nathan@oregon-state