I have a class that I would like to store a static std::string
that is either truly const or effectively const via a getter.
I've tried a couple direct approaches
1.
const static std::string foo = "bar";
2.
const extern std::string foo; //defined at the bottom of the header like so
...//remaining code in header
}; //close header class declaration
std::string MyClass::foo = "bar"
/#endif // MYCLASS_H
I've also tried
3.
protected:
static std::string foo;
public:
static std::string getFoo() { return foo; }
These approaches fail for these reasons respectively:
const string MyClass::foo
of non-literal typefoo
-- it doesn't seem to like combining extern
with const
or static
The reason I would like to have the declaration within the header rather than source file. This is a class that will be extended and all its other functions are pure virtual so I currently have no other reason than these variables to have a source file.
So how can this be done?
static const : “static const” is basically a combination of static(a storage specifier) and const(a type qualifier). Static : determines the lifetime and visibility/accessibility of the variable.
A constant expression is an expression that can be fully evaluated at compile time. Therefore, the only possible values for constants of reference types are string and a null reference.
An example of using static const member variables in C++ is shown below with common types (integer, array, object). Only one copy of such variable is created for its class. The variable cannot be modified (it is a constant) and is shared with all instances of this class.
One method would be to define a method that has a static variable inside of it.
For example:
class YourClass
{
public:
// Other stuff...
const std::string& GetString()
{
// Initialize the static variable
static std::string foo("bar");
return foo;
}
// Other stuff...
};
This would only initialize the static string once and each call to the function will return a constant reference to the variable. Useful for your purpose.
You can only initialize a static const value in the constructor for integer types, not other types.
Put the declaration in the header:
const static std::string foo;
And put the definition in a .cpp file.
const std::string classname::foo = "bar";
If the initialization is in the header file then each file that includes header file will have a definition of the static member. There will be linker errors as the code to initialize the variable will be defined in multiple .cpp files.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With