0

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.

Ankit
  • 3,856
  • 1
  • 10
  • 16
  • 1
    soo `FileReader::FileReader(const std::string& iniFilePath) : params(Params::createFromIniFile(iniFilePath)) {}`? – KamilCuk Nov 07 '22 at 22:31

1 Answers1

2

You are doing the initialization in the wrong place. Once you've enter the body of the constructor all class members have already been initialized. What you need to do is initializer params in the class member initialization list like

FileReader::FileReader(const std::string& iniFilePath) : 
    params(Params::createFromIniFile(iniFilePath))
{
    // constructor body
}
NathanOliver
  • 171,901
  • 28
  • 288
  • 402
  • Thank you, this works. But, I am confused with this: in the static method `createFromIniFile`, I create a new instance of Params struct and return that. is the const Params object initialized because of the return ? – Ankit Nov 08 '22 at 07:49
  • 1
    @Ankit `params` is initialized with the result of evaluation the expression `Params::createFromIniFile(iniFilePath)` which is to say it is initialized with the result of calling the function `createFromIniFile` i.e. with the returned value from that function call. – bolov Nov 08 '22 at 11:05