static constants in classes

Posted on 2011-05-09
Medium Priority
Last Modified: 2012-05-11
I tend to keep constants needed by a data structure/object as static constants within the class itself, instead of keeping in c style header file, as it helps to keep a cohesive class. What is a better practice? what are the possible cons?
Question by:Mydeen Yussouf
LVL 53

Expert Comment

ID: 35726322
Do those constants need to be exposed in the header file ? Can you move them to a .cpp file instead ?

Are these constants stand-alone, or are they part of a group of constants ? In other words, can you group related constants in an enum ?

What kind of constants are we talking about here ? Are they true constants ? Or are they rather configuration that you might change depending on the platform or specific conditions ? Thinking about the specific usage of these constants, would it make sense to get them from a configuration file ? Or to configure them with a tool like autoconf ?

Assisted Solution

theKashyap earned 252 total points
ID: 35726335

There are no possible cons. What you do is a good practice. Although there are other options, perhaps better suited, but depending on the situation.

For the sake of argument one can say that if you declare the consts inside the class itself instead of a separate header, AND someone else needs those consts then they're forced to include the class declaration just to get the consts instead of just a #include of a header.
Well, this is rubbish of course because it doesn't make sense to declare the consts inside one class's header if another class needs them as well.

Another option is to use anonymous namespace
You declare the consts inside a class coz you don't want to pollute the global namespace.
If you don't want to pollute even the class declaration, you have the option of polluting an anonymous namespace instead. Which by definition is local to compilation and can't be "polluted".
class X {
   const int AAA = 10;
   X() { cout << "My const usage" << AAA << endl; }


// can be replaced with:
namespace {
   const int AAA = 10;

class X {
   X() { cout << "My const usage" << AAA << endl; }

// which in turn can be replaced with:
// consts.h
namespace {
   const int AAA = 10;

// X.cxx
#include "consts.h"
class X {
   X() { cout << "My const usage" << AAA << endl; }

Open in new window

Or the declaration of the const (along with namespace) can be moved a separate header say consts.h and add #include "consts.h" to the class header.

Advantage being that just in case someone other class, which we did not anticipate at the time of writing the code, wants to use these consts, it can #include "consts.h" safely.
Given that anonymous namespace is available/accessible only within the compilation unit it's defined in, you won't have name-clashes. Which you would have e.g. if you declared the consts in global namespace inside a header and #included it into 2 different .cxx (compilation units).

LVL 22

Accepted Solution

ambience earned 248 total points
ID: 35726597
>> What is a better practice? what are the possible cons?

The possible con in type-safety (and that depends on how you use constants). For example, a const like this is probably not going to hurt that much

const int kBufferSize = 1024;
char buffer[kBufferSize];

However if you were to do something like this

class HttpCache {
const int kCacheRevalidate = 0;
const int kForceFetch = 1;

bool download(std::string url, int flags = kCacheRevalidate);

Here the flags is not type-safe in that someone could blow up things without warning

download(..., 0xdead);

You could use enums - but the problem with enums is that they pollute the namespace, so for example

class HttpResource {
enum DownloadOptions {
    authorize, simple
enum UploadOptions {
    authorize, simple
bool download(string url, DownloadOptions options = simple)
bool upload(string url, UploadOptions options = simple)

Here the two will collide and this code wont compile. The work around to use different nomenclature. However, try putting enums on namespace scope and it quickly goes out of hand. Note: because of the way enums work, even this is not completely type-safe just much better than the first option.

Rules have changes in new c++ standards wrt enums and if im not mistaken this kind of pollution is addressed. Plus now you can scope enum literals like


which was not allowed in earlier standard, except that some compilers implemented non-standard extensions.


Featured Post

Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article shows you how to optimize memory allocations in C++ using placement new. Applicable especially to usecases dealing with creation of large number of objects. A brief on problem: Lets take example problem for simplicity: - I have a G…
Article by: evilrix
Looking for a way to avoid searching through large data sets for data that doesn't exist? A Bloom Filter might be what you need. This data structure is a probabilistic filter that allows you to avoid unnecessary searches when you know the data defin…
The viewer will learn how to use the return statement in functions in C++. The video will also teach the user how to pass data to a function and have the function return data back for further processing.
The viewer will be introduced to the technique of using vectors in C++. The video will cover how to define a vector, store values in the vector and retrieve data from the values stored in the vector.
Suggested Courses

864 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question