Maksim Dmitriev
Maksim Dmitriev

Reputation: 6209

State flags in C++

I always make a class called Constants in Java to store constant values which will be used in an application.

For all the classes of the application

class Constants {

    public static final int GOOD_RES = 1;
    public static final int BAD_RES = 0;
    public static final int FILE_NOT_READ = 10;
    // To be continued
}

or for a single class

class SomeClass {

    private static final int GOOD_RES = 1;
    private static final int BAD_RES = 0;
    private static final int FILE_NOT_READ = 10;
    // To be continued
}

How to do the same in C++? I can make a class in a header file with declarations and place definitions in a CPP file. For example.

Header file.

class const_values {
    const static int GOOD_STATE = 1;
    const static int BAD_STATE = 2;
    const static string s;
}

CPP file

string const_values::s = "lorem ipsum";

Is it OK?

Upvotes: 0

Views: 656

Answers (2)

John Dibling
John Dibling

Reputation: 101506

Using a class for nothing but static constants is legal C++, but I would suggest that there are usually better ways to accomplish your goal.

First and foremost is the use of a namespace:

namespace values
{
    const static int GOOD_STATE = 1;
    const static int BAD_STATE = 2;
    const static string s;  // you can never make this anything but empty, by the way
};

If for some reason you simply must use a class, another (maybe not better) way to so it is by using enums:

class values
{
public:
  enum {GOOD_STATE = 1, BAD_STATE = 2};
};

One advantage to using a namepsace is you can make that namespace un-named. This has the effect of making the names declared within the namespace available at global scope, but only in the translation unit(s) in which they are defined. Hence no collision across other translation units, and maybe less need for a silly name for the namespace.

Upvotes: 2

Bojan Komazec
Bojan Komazec

Reputation: 9536

Use namespace for that:

constants.h:

#include <string>
namespace Constants
{
    const int GOOD_STATE = 1;
    const int BAD_STATE = 2;
    const std::string str("test");
}

main.cpp:

#include <iostream>
#include "constants.h"
int main(int argc, char** argv)
{   
    std::cout << Constants::GOOD_STATE << " " << Constants::str << std::endl;
}

Output: 1 test

Upvotes: 4

Related Questions