I am experimenting with the const and static keywords and am getting stuck with my class design.
The class FileReader
contains a struct Params
with its own default constructor and a static method to initialize the member variables of the struct. The parameters in Params
struct need to be initialized only once when the class is initialized. Therefore, it is marked as const
. I understand that, normally, that the members of the struct can be modified from a non-static function if they are declared mutable
.
- My question is: Is it possible to modify the const struct members from a static member function? If so, how? If not, what would be the best/better way of initializing a const struct when the parameters can only be initialized during runtime or when a file is read?
The class is defined in the header as follows:
class FileReader
{
public:
FileReader(const std::string& iniFilePath);
private:
struct Params
{
private:
Params() = default;
public:
static Params createFromIniFile(const std::string iniFilePath);
// some member variables
};
const Params params; // will be initialized when class is initialized!
};
The static method is defined in cpp as follows:
auto FileReader::Params::createFromIniFile(const std::string iniFilePath) -> Params
{
Params result;
// parse ini file
readFile(iniFilePath);
// initialize params
...
return result;
}
FileReader::FileReader(const std::string& iniFilePath)
{
//call static initializer
params = Params::createFromIniFile(iniFilePath); // error: params cannot be initialized this way
}
I have tried the approach mentioned here using a fake pointer and it worked, but I want to avoid using this
and raw pointers.