I have a set of functions that work on a file. Originally I made it into a class, with the only private member being a static const std::string which was the name of the file. The user used these functions by creating an object and calling functions from it. However, I think I’m going to switch to using a namespace, since it’s just a set of functions and makes more sense. The only problem is that I still would like to keep that constant string. Would doing something along these lines be fine?
namespace FileHandler {
// Functions to do stuff with file
const std::string FILE_NAME;
}
I have a separate implementation file for the namespace, but I’m wondering if the loss of encapsulation from having the file name be a private member in a class is worth using the namespace instead.
You can do similar things but they will have different semantics.
In a class, a static variable is a declaration, not a definition, it still requires a definition outside of the class; a variable declaration in a namespace is a definition unless you mark in as
externand don’t provide an initializer.In your case it doesn’t make too much difference as
constvariables have internal linkage by default so you can have multiple definitions in a program (one per translation unit) without problems.E.g.
is (in some ways) equivalent to:
If you did this, you would be declaring
FILE_NAMEas an empty string. You couldn’t redeclare it elsewhere in the same translation unit.You could, though, do this.
Each translation unit would have its own version of
Test::FILE_NAMEbut they would all be consistent.