473,406 Members | 2,356 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,406 software developers and data experts.

question about constants in C++

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.

1.)

I have seen people declare in their .h file

static const int myVariable;

And then in their .cpp put the definition.

myVariable = 10;

2.) Is it appropriate if the variable is only to be used in a class to put
that definition in the class so as to scope it to that class only?
umm, but then should it be private with an accessor?

So for example,

class MyClass {

public:
static const int myVariable = 10;

private:

}

3.)

Is it best to put it in a blank namespace in the .cpp file to keep the scope
to that file only?

So for example,

namespace {

static const int myVariable = 10;

}

I appreciate comments on this matter.
thanks for your help.
Jul 22 '05 #1
8 2818
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
Jul 22 '05 #2
john smith wrote:
class MyClass {

public:
static const int myVariable = 10;

private:

}


AFAIK this is not supported by all compilers, in fact initializing an object
inside the class body.
Jul 22 '05 #3

"Jonathan Mcdougall" <jo***************@DELyahoo.ca> wrote in message
news:uF*********************@wagner.videotron.net. ..
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;
};


[snip]

I assume you meant "static const float PI;"?
Jul 22 '05 #4
Matthias Käppler wrote in news:co*************@news.t-online.com in
comp.lang.c++:
john smith wrote:
class MyClass {

public:
static const int myVariable = 10;

private:

}


AFAIK this is not supported by all compilers, in fact initializing an
object inside the class body.


Initializing a static intergral constant member (such as the above)
in the body of its class is supported by *all* Standard conforming
C++ compilers.

If you have a "c++" compiler that doesn't allow this:

- It was probably writen prior to the first C++ Standard (1998).
- Get a better (newer) compiler.

Rob.
--
http://www.victim-prime.dsl.pipex.com/
Jul 22 '05 #5
Rob Williscroft wrote:
Initializing a static intergral constant member (such as the above)
in the body of its class is supported by *all* Standard conforming
C++ compilers.

If you have a "c++" compiler that doesn't allow this:

- It was probably writen prior to the first C++ Standard (1998).
- Get a better (newer) compiler.

Rob.


From Bjarne Stroustrup's C++ Technical FAQ:

"I tend to use the "enum trick" because it's portable and doesn't tempt me
to use non-standard extensions of the in-class initialization syntax."

Sounds pretty clear to me.

Regards,
Matthias
Jul 22 '05 #6
Rob Williscroft wrote:
Matthias Käppler wrote in news:co*************@news.t-online.com in
comp.lang.c++:
john smith wrote:
class MyClass {

public:
static const int myVariable = 10;

private:

}


It's also problematic because it only works with static constant integers.
For e.g. a float you'd have to use the classic syntax.
Jul 22 '05 #7
Matthias Käppler wrote:
"I tend to use the "enum trick" because it's portable and doesn't tempt me
to use non-standard extensions of the in-class initialization syntax."

Sounds pretty clear to me.

Regards,
Matthias


I think I misinterpreted the sentence. What he probably meant was that
non-standard extensions exist, which may lead to many people using them
(which is generally a bad thing).

So don't mind my last post, it was incorrect.

Regards,
Matthias
Jul 22 '05 #8
"Rob Williscroft" <rt*@freenet.co.uk> wrote...
[..]
Initializing a static intergral constant member (such as the above)
in the body of its class is supported by *all* Standard conforming
C++ compilers.
Oh, yeah. Just like all other things the Standard prescribes.
If you have a "c++" compiler that doesn't allow this:

- It was probably writen prior to the first C++ Standard (1998).
- Get a better (newer) compiler.


Such statements are not constructive. (a) There is no such thing in the
world as a "Standard conforming C++ compiler". Every compiler has some
quirks (and bugs) in it and the Standard keeps changing. And (b) getting
"a better (newer) compiler" is not always possible in the current (or any
for that matter) market conditions; it doesn't just cost money (which is
often so), it costs time, it costs customers who don't want to change.

V
Jul 22 '05 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
by: Sugapablo | last post by:
I'm trying to use the Const statement to define a group of constants. I would like different groups of constants, one for each language (such as english, spanish, etc.) Depending on a variable...
4
by: gabriel | last post by:
Greetings, I am working on a project and cannot choose the best way to achieve this : I got a method which returns an error code like this : DISK_FULL or PERMISSION_DENIED. Those are...
13
by: poison.summer | last post by:
Hello If I have an enum definition for instance typedef enum { F0 = 0, F1 = 1, F2 = 2, F3 =3
2
by: yawnmoth | last post by:
The PHP license states the following: 4. Products derived from this software may not be called "PHP", nor may "PHP" appear in their name, without prior written permission from group@php.net. ...
4
by: D. Yates | last post by:
Hi all, Is there a place in the .NET framework where simple time constants are defined? For example: How many days are there in a week? Hours in a day? Minutes in an hour? Seconds in a...
10
by: Steven W. Orr | last post by:
I saw this and tried to use it: ------------------><8------------------- const.py------------- class _const: class ConstError(TypeError): pass def __setattr__(self,name,value): if...
3
by: Steven W. Orr | last post by:
This is all an intro learning experience for me, so please feel free to explain why what I'm trying to do is not a good idea. In the Cookbook, they have a recipe for how to create global...
6
by: lazy | last post by:
hi, I have some constants defined in a php script say config.php. I want to use the variables there defined in other scripts. couple of questions regd that: 1. Is there an alternative to...
3
by: Microsoft | last post by:
Hi I have a c# program that continually runs 24/7 and performs a variety of tasks based on a timer. There is one routine that hangs every Saturday morning without fail. If I restart the...
54
by: shuisheng | last post by:
Dear All, I am always confused in using constants in multiple files. For global constants, I got some clues from http://msdn.microsoft.com/en-us/library/0d45ty2d(VS.80).aspx So in header...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.