Nico Schlömer
Nico Schlömer

Reputation: 58761

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?

Upvotes: 3

Views: 165

Answers (2)

PiotrNycz
PiotrNycz

Reputation: 24392

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) {}
};

Upvotes: 1

Kerrek SB
Kerrek SB

Reputation: 476990

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.

Upvotes: 2

Related Questions