3

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)
Waqar
  • 8,558
  • 4
  • 35
  • 43
YAKOVM
  • 9,805
  • 31
  • 116
  • 217
  • Tip: You can use `"Common/Data/input.txt"`. – Burak Aug 09 '20 at 13:41
  • @Yakov In current SO this can be considered opinion based. In yesterdays SO there are some threads that have some considerations about this issue, like [this one](https://stackoverflow.com/q/2043493/6865932) or [this one](https://stackoverflow.com/q/5620256/6865932) – anastaciu Aug 09 '20 at 13:45

2 Answers2

4

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.

r3mus n0x
  • 5,954
  • 1
  • 13
  • 34
  • Is there any difference between declaring the variable as `static` or as this anonymous method? – Burak Aug 09 '20 at 13:44
  • 1
    @Burak, it is recommended to prefer unnamed namespace to `static` for global variables/functions in C++. At some point there was even a plan to deprecate such usage of `static` in C++. See more [here](https://stackoverflow.com/questions/4726570/deprecation-of-the-static-keyword-no-more). – r3mus n0x Aug 09 '20 at 13:48
3

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.

Waqar
  • 8,558
  • 4
  • 35
  • 43