Hex Crown
Hex Crown

Reputation: 753

C++ private static constexpr member variables

So I'm wondering, given the simple class:

//Foo.h
class Foo {
private:
    static constexpr int bar = 0;

public:
    int do_something();
};

//Foo.cpp
int Foo::do_something() {
    return 5 + bar;
}

Would it be reasonable to completely remove bar from the header as its a private static constexpr value thats never used in the header file?

If it were to just be floating at the top of the cpp file instead, it would effectively provide the same functionality, with the added bonus of cleaning up the header file a little.

Are there any reasons not to do this?

Edit: For clarification, these variables may be used in one or more functions, one or more times, and NEVER in the header file.

In my use case, these variables are constant limits/vecs, an example:

static constexpr float rotLimitVertical = to_rad(90.0f);
static constexpr float rotLimitHorizontal = to_rad(360.0f);

static const glm::vec3 right    = {1, 0, 0};
static const glm::vec3 up       = {0, 1, 0};
static const glm::vec3 forward  = {0, 0, 1};

which I would like to keep at the top of the file to make them easy to tweak if need be (especially in the case the variable is only used in one function, sure it may make sense to change it to a local variable, but that makes it more annoying to find to adjust).

Upvotes: 1

Views: 3643

Answers (1)

R Sahu
R Sahu

Reputation: 206557

Are there any reasons not to do this?

I think it is better to move it to the .cpp file. You can make it:

  1. A file scoped static variable, or
  2. A variable in the anonymous namespace in the .cpp file, or
  3. A variable in the namespace that is specific to the .cpp file.

Option 1

static constexpr int bar = 0;

Option 2

namespace
{
   constexpr int bar = 0;
}

Option 3

namespace MyFile_Namespace
{
   constexpr int bar = 0;
}

Upvotes: 4

Related Questions