Re: question about constants in C++
From: Jonathan Mcdougall (jonathanmcdougall_at_DELyahoo.ca)
Date: 11/25/04
- Next message: Victor Bazarov: "Re: overloading in C"
- Previous message: uday: "virtual constructor"
- In reply to: john smith: "question about constants in C++"
- Next in thread: Method Man: "Re: question about constants in C++"
- Reply: Method Man: "Re: question about constants in C++"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
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
- Next message: Victor Bazarov: "Re: overloading in C"
- Previous message: uday: "virtual constructor"
- In reply to: john smith: "question about constants in C++"
- Next in thread: Method Man: "Re: question about constants in C++"
- Reply: Method Man: "Re: question about constants in C++"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Relevant Pages
|