At class instantiation, I would like to read data from a file and process it into a number of class objects. What I did so far (and works well) is
myData::myData(const std::string & file):
data1_(this->read(file)),
processedData1_(this->createProcessedData1_(data1_)),
processedData2_(this->createProcessedData2_(data1_)),
processedData3_(this->createProcessedData3_(data1_))
{
}
In a different class, the read() method creates more than one raw data object. In this case, I don’t know how to pack things into the initializer list, so I’m doing something along the lines of
myData::myData(const std::string & file):
data1_(),
data2_(),
processedData1_(),
processedData2_(),
processedData3_()
{
this->read(file); // fills data1_, data2_
processedData1_ = this->createProcessedData1_(data1_, data2_);
processedData2_ = this->createProcessedData2_(data1_, data2_);
processedData3_ = this->createProcessedData3_(data1_, data2_);
}
What I don’t like about this approach is that
- the data is initalized twice: once (void) in the initializer list, once filled with actual content in the constructor; and that
- I cannot mark any of the (processed) data objects as
const.
Is there a way to organize the object creation such that it all happens in the initialization list?
You may think about splitting the data loading / processing in a factory-like static method that in turn constructs a myData instance (passing the processedData*_ values as constructor params).
This way you can keep the loading and processing separate from the class that may end up just storing the results and possibly provide further processing or accessors to parts of the data.
Could something like
work for you?
I’m assuming you don’t need to keep state when loading and processing data. If this isn’t the case you can make
readandcreateProcessedData*members of aMyDataLoaderclass.