static constants in classes

Posted on 2011-05-09
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:olmuser
    LVL 53

    Expert Comment

    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 ?
    LVL 6

    Assisted Solution


    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

    >> 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.


    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone.

    Featured Post

    How to run any project with ease

    Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
    - Combine task lists, docs, spreadsheets, and chat in one
    - View and edit from mobile/offline
    - Cut down on emails

    Suggested Solutions

    Written by John Humphreys C++ Threading and the POSIX Library This article will cover the basic information that you need to know in order to make use of the POSIX threading library available for C and C++ on UNIX and most Linux systems.   [s…
    What is C++ STL?: STL stands for Standard Template Library and is a part of standard C++ libraries. It contains many useful data structures (containers) and algorithms, which can spare you a lot of the time. Today we will look at the STL Vector. …
    The goal of the tutorial is to teach the user how to use functions in C++. The video will cover how to define functions, how to call functions and how to create functions prototypes. Microsoft Visual C++ 2010 Express will be used as a text editor an…
    The viewer will learn additional member functions of the vector class. Specifically, the capacity and swap member functions will be introduced.

    779 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

    Need Help in Real-Time?

    Connect with top rated Experts

    12 Experts available now in Live!

    Get 1:1 Help Now