Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

const initialization of several data members

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?

like image 766
Nico Schlömer Avatar asked Mar 07 '26 09:03

Nico Schlömer


2 Answers

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.

like image 196
Kerrek SB Avatar answered Mar 09 '26 00:03

Kerrek SB


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) {}
};
like image 21
PiotrNycz Avatar answered Mar 08 '26 22:03

PiotrNycz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!