I would like to have a C++ class that gets initialized from a file that contains a bunch of data, reads the data, and stores it as const data members.
What I currently do is
MyClass(const std::string & fileName):
datum0(),
datum1(),
datum2()
{
this->read(fileName);
// read() sets all datumX data members.
}
This has the disadvantage that the datumXs cannot be marked const anymore since they are set up after the actual initialization step.
What would be a good pattern here?
Separate parsing and construction:
struct MyClass
{
int const a;
int const b;
MyClass(int a_, int b_) : a(a_), b(b_) { }
};
MyClass readMyClass(std::istream & is)
{
int a, b;
// ...
return MyClass(a, b);
}
Now you can say:
std::ifstream is("data.bin");
MyClass mc = readMyClass(is);
You can also make the reader function a static class member function and the constructor private if you prefer.
Instead of set of datumX members - use struct with these members which have constructor from file. And make this struct const data member of your class:
class MyClass {
...
struct MyData {
MyData(const string& filename) { read(filename); }
void read(const string& filename);
int datum1;
int datum2;
...
};
const MyData myData;
MyClass(const string& filename) : myData(filename) {}
};
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