Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Design pattern for const structures?

Tags:

c++

constants

Let's say I have to read some configuration files to set fields of a structure. As soon as the file has been read and the structure initialized, its field's values should not be changed.

I read many times it was bad to have structures with const fields. But then, how to make sure its fields are not changed ?

Let's come back to the case described above. I have a function supposed to read a file given as argument and instantiate the structure with the values coming from the file. Ideally, this function would return this structure by value. But if I do so with non constant fields, the client can change the values.

A solution would be to have a class to wrap the file reader, with a non const member to the read structure, and a const accessor to read the structure and its fields. But it not very satisfying.

Is there an idiom for this situation?

like image 650
Oodini Avatar asked Sep 03 '26 14:09

Oodini


1 Answers

As @NathanOliver commented, you can make all the parameters private members, and expose public getters (and no setters).

Something like:

#include <string>

class Config {
public:
    int   GetP1() const { return m_p1; }
    float GetP2() const { return m_p2; }

    bool LoadFromFile(std::string const& filename) {
        // populate m_p1, m_p2 etc.
        return true;
    }

private:
    int   m_p1{};
    float m_p2{};
};

Note that there is also a public method to initialize the configuration from the file.

like image 71
wohlstad Avatar answered Sep 06 '26 05:09

wohlstad