Re: question about constants in C++

From: Jonathan Mcdougall (jonathanmcdougall_at_DELyahoo.ca)
Date: 11/25/04


Date: Wed, 24 Nov 2004 21:43:41 -0500

john smith wrote:
> I have a question about the best way to use constants in C++. There seem to
> be variations in the way that they are used, and I am confused as to what I
> should be using. Basically since the constant is used in only one class,
> should I try to scope it to just that class? to the file?
> what are the thoughts out there.

If a constant is part of the class :

   1. if the constant will be the same for all objects of that class (PI
      for a class Math for example), make it a static constant member.

       // my_math.h
       class Math
       {
       private:
         const float PI;
       };

       // my_math.cpp
       float Math::PI = 3.1416;

      Whether the constant is public or not depends on your design.

   2. if the constant will change depending on the instances, make it a
      constant member :

       // car.h
       class Car
       {
       private:
         const int max_speed;

       public:
         Car(int ms);
       };

       // car.cpp
       Car::Car(int ms)
         : max_speed(ms)
       {
       }

If the constant is not part of a class, make it part of a namespace if
possible to avoid name clashes.

In general, always try to keep scopes as small as possible. For
example, it is possible for the constant Math::PI to be declared at file
scope, but it is a better design to make it part of the class it is
meant to be used with.

Jonathan



Relevant Pages

  • Re: eye pieces
    ... First, please let me agree with you and Steve that in practice, ... the tolerances or variations that attach to a spec like "200mm f/6" ... Just to clarify the situation about the stated specs for my scope. ...
    (sci.astro.amateur)
  • Re: Wild Stereoscope Models
    ... more variations of this particular scope? ... 1) The standard configuration (left amd right optical path ... centerline of objective lens group). ...
    (sci.techniques.microscopy)
  • Re: What do you think of this scope? (Tek)
    ... That's a great scope and mainframe. ... Owned several variations over the ... providing the CRT is still in good shape and can hold a ...
    (sci.electronics.design)
  • Re: Adventures with a new scope and difficulty of finding things!
    ... Jonathan G Wrote: ... > peek at the Orion Nebula but seemed to spend ages shuffling the scope ... > Chichester planetarium http://www.astronomyknowhow.com/ It's a fair ... Nytecam ...
    (uk.sci.astronomy)
  • Re: Want to buy, but confused about oscilloscopes
    ... John Smith wrote: ... >>continue to be aware that the sampling rate slows down as you display ... The only scope I had access to was a 54600. ... the single-shot sampling rate is a miserable 40MSPS or something low ...
    (sci.electronics.design)