Path: utzoo!attcan!uunet!cs.utexas.edu!yale!mintaka!bloom-beacon!athena.mit.edu!bjaspan From: bjaspan@athena.mit.edu (Barr3y Jaspan) Newsgroups: comp.lang.c++ Subject: Re: Constant member variables in TC++ Message-ID: <1990Nov11.181752.8098@athena.mit.edu> Date: 11 Nov 90 18:17:52 GMT References: Sender: daemon@athena.mit.edu (Mr Background) Reply-To: bjaspan@athena.mit.edu (Barr3y Jaspan) Organization: Massachusetts Institute of Technology Lines: 44 In article , ahuttune@niksula.hut.fi (Ari Juhani Huttunen) writes: |> class X { |> const int const_int; |> }; |> |> Gives a warning: constant field not initialized. |> [but initializing it...] |> |> Gives an error: can't initialize a field. This is an annoying side-effect of separate compilation and the semantics of const variables. The contraints: 1) By definition, a const variable cannot be assigned to. In the first example, you aren't initializing it, which means you are going to have a "constant" garbage value. 2) You can't put an initialization in a header file because then the compiler would have no way of knowing WHICH of the many .C files it was #included in was the "main .C file" in which the initialization should take place -- therefore, the initialization would probably take place more than once. Hmmm... now that I think about (2), it doesn't seem right. In this particular case, the compiler could easily do the initialization as implicit behavior in every constructor (assuming it did the initialization at all instead of just replacing all occurrences of that field with an immediate constant). Anyway, the only way I know of to get around this problem is to declare an enum with the constant you want. It's a kludge but it works. So, for example, class X { enum { const_int = 10 }; int by_the_way_this_works_too[const_int]; }; will make "const_int" be a constant 10 and even declares a constant-length array in the process (which there is also no other way to do). Note that enums do not have to be named. -- Barr3y Jaspan, bjaspan@mit.edu