Path: utzoo!utgpu!news-server.csri.toronto.edu!rpi!crdgw1!uunet!island!grenada!roger From: roger@grenada.island.COM (Roger Corman) Newsgroups: comp.lang.c++ Subject: Re: const vs. static in class declaration Keywords: const, static, class constants Message-ID: <139@grenada.island.COM> Date: 30 Mar 91 00:01:50 GMT References: <286@dayton.stanford.edu> Organization: Island Graphics, Santa Rosa, California Lines: 66 In article <286@dayton.stanford.edu> lma@dayton.Stanford.EDU (Larry Augustin) writes: >I have a number of integer constants that are part of a class. What >is the correct way to go about doing this? I have been using: > > > class foo { > private: > ... > protected: > ... > public: > const int ID = 258; > const int NUMBER = 259; > const int IPORT = 260; > ... > }; > >But I've been told that this only works in g++, and isn't standard. I >would like to avoid doing anything in my my application that isn't >portable. > Your way does not work with CFront. Two ways to do this (using 'static const' and enum) are shown in this example. Only the enum lets you actually include the initializer value in the class definition. The static const requires that the initializer be outside the class definition (usually the not in an #include file). ------------------------------------ #include class foo { public: foo(){} static const int ID; enum {IPORT=100}; }; const int foo::ID = 200; main() { foo f; cout << f.ID << "\n"; cout << f.IPORT << "\n"; cout << foo::IPORT << "\n"; cout << foo::ID << "\n"; } ------------------------------ Roger Corman Island Graphics 149 Stony Circle, Suite 200 Santa Rosa, CA 95401 (707)523-4465 {uunet,sun,ucbcad!island!roger} class Disclaimer { private: ObscureStuff employerOpinions; public: UsefulAdvice myOpinions[MAXINT]; };