Path: utzoo!utgpu!attcan!uunet!lll-winken!lll-ncis!helios.ee.lbl.gov!pasteur!ucbvax!decwrl!labrea!rutgers!att!ulysses!andante!alice!ark From: ark@alice.UUCP (Andrew Koenig) Newsgroups: comp.lang.c++ Subject: Re: static members Message-ID: <8695@alice.UUCP> Date: 7 Jan 89 05:01:32 GMT References: <701@cadillac.CAD.MCC.COM> Organization: AT&T Bell Laboratories, Liberty Corner NJ Lines: 69 In article <701@cadillac.CAD.MCC.COM>, rpj@redcloud.cad.mcc.com (Rich Johns) writes: > In Stroustroup on page 275, section 8.5.1 it states: > > "No initializer can be specified for a static member, > and it cannot be of a class with a constructor." > This could mean two things(at least): > 1) if a class has a constructor, that class may NOT have > static members. > 2) You cannot have a static data member which needs a > constructor. (2) is correct. The reason for this is that the definition of a static data member appears as part of the class definition, which is generally replicated in several modules. If the member requires a constructor, that constructor would effectively be called in each module, thus initializing the member many times. > After discussing this with someone, I am inclined to > think number 2 is correct. As such are the following > assumptions correct: > a) a static data member is allowed, as long as: > 1) the member does not require a constructor. > 2) the member is private It doesn't have to be private. > b) a static const data member is allowed, as long as: > 1) the member does not require a constructor. > 2) the member is private It doesn't have to be private. > c) a static const data member CAN have an initial value. Yes indeed. > d) a static function member is not allowed. It would make sense, wouldn't it? class Widget { static int n; public: Widget() { n++; /* other stuff */ } ~Widget() { n--; /* other stuff */ } static int count() { return n; } /* other stuff */ }; This is an example of a Widget class that, among other things, counts how many Widgets there are in the universe. Thus if I say Widget x; cout << x.count() << "\n"; it prints 1 (unless there are other Widgets I didn't mention). Of course if there aren't any Widgets at all I can't use this notation to count them, but I should be able to call Widget::count. Anyway, it's an interesting idea, but not presently implemented. -- --Andrew Koenig ark@europa.att.com