473,569 Members | 2,731 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 2826
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******** *************@w agner.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
1205
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 (cookie, querystring, etc.) I would like the constants to be defined differently. One thing I tried was:...
4
2558
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 constants defined in a class named "Constants" : public static byte DISK_FULL = 1;
13
3046
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
1829
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. You may indicate that your software works in conjunction with PHP by saying "Foo for PHP" instead of calling it "PHP Foo" or "phpfoo" As the author...
4
2004
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 minute? None of these are going to change, so they are obviously constants. Now I
10
1563
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 self.__dict__.has_key(name): raise self.ConstError, "Can't rebind const(%s)"%name self.__dict__=value
3
1251
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 constants. ----------------- class _const: class ConstError(TypeError): pass def __setattr__(self,name,value): if self.__dict__.has_key(name):
6
1623
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 including config.php and declaring the variables that will be used as global. This seems very inefficient. 2.Moreover these variables are constants, is...
3
1676
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 program throughout the week is still hangs. I can restart it immediatly after the hang and it runs fine until next Saturday. There is nothing different...
54
3558
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 file writing: const double PI = 3.14; Every time using it, include the header file.
0
7612
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
7924
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
8122
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
1
7673
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
7970
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
1
5513
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 presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
3653
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3640
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1213
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.