0

Given a class which has certain private, constants (e.g., configuration), should these (A) be included in the declaration of the class (in the private section) or (B) should it be "hidden" with the definition (in the source file).

Option A

//MyClass.hpp
class MyClass
{
public:
    int foo(int a);

private:
   static constexpr int kConfig1 = 10;
   static constexpr int kConfig2 = 20;
};

//MyClass.cpp
#include "MyClass.hpp"

int MyClass::foo(int a)
{
    return (a * kConfig1) + kConfig2;
}

Option B

//MyClass.hpp
class MyClass
{
public:
    int foo(int a);
};

//MyClass.cpp
#include "MyClass.hpp"

namespace //Similar to C "static" from my understanding
{
    constexpr int kConfig1 = 10;
    constexpr int kConfig2 = 20;
}

int MyClass::foo(int a)
{
    return (a * kConfig1) + kConfig2;
}

I understand that, if the constants are use by inline functions within the header itself, they also need to be declared/defined in the header. But, since they are used only from within the source, is there a reason not to declare/define the constants only in the source?

The only information I think you "loose" in this case is that the constants are logically "attributes" of the MyClass class.

The only other "con" I can think of for option B is that, from a maintenance (and understanding) perspective, all the information about a class (including its constant configuration data) can be found simply by looking in the header.

1 Answer 1

1
It depends on why you want it there.

Put everything you need to describe the public interface into the public header, including all includes necessary to compile it stand-alone.

If you need to share a private interface between files, put everything you need to describe it (which is an extension of the public interface) into the private header, including all includes necessary to compile it stand-alone.

Everything else doesn't belong in any header.

Rationale:

Separating things this way limits what will be included, resulting in many benefits:

  • Faster compilation, as fewer things irrelevant at that level of abstraction / to consumers are included, which would have to be parsed and compiled.
  • Inadvertent dependencies on implementation details are less likely, as those are less exposed.
  • Less re-compilation as changes to the implementation are less likely to land in the header.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.