best practice - where should const data for the class should be defined

Viewed 213

I write a class which defines and uses const string (This string defines a path or a part of the path) Where should I define it : in cpp or h? should it be part of the class? For now this data is used only inside internal member functions. Which option is better?

myClass.h
    // const std::string PATH = "Common\\Data\\input.txt" (1)
    class MyClass
    {
      public:
        // const std::string m_path = "Common\\Data\\input.txt" (2)
      private:
        // const std::string m_path = "Common\\Data\\input.txt" (3)
    }
myClass.cpp
// const std::string PATH = "Common\\Data\\input.txt"(4)
2 Answers

If this constant is only used in one class and it's the same for all instances of the class, you can define it in an unnamed namespace in your .cpp file:

namespace {
    const std::string PATH = "Common\\Data\\input.txt";
}

This way it will be only accessible inside single .cpp file and won't cause any potential name conflicts during linking if any other file defines a similar variable.

The main goal of this approach is to use the smallest possible scope for the definition to reduce redundant implicit dependencies. For example, the clients of your class won't have to be recompiled in case this constant is changed.

I write a class which defines and uses const string (This string defines a path or a part of the path) Where should I define it : in cpp or h?

It depends.

Is the value of string m_path same for all instances of class?

  • If yes, then it should either be static const, or just defined globally or in an unnamed namespace in the ".cpp" file.

Is the value of string m_path different for every / some instances of the class?

  • If yes, then it should be a private const data member, which is initialized in the constructor.

For now this data is used only inside internal member functions which option is better?

Then it should be private, not public.

Related