I want to create an immutable data structure which, say, can be initialized from a file.
class Image {
public:
   const int width,height;
   Image(const char *filename) {
     MetaData md((readDataFromFile(filename)));
     width = md.width();   // Error! width  is const
     height = md.height(); // Error! height is const
   }
};
What I could do to fix the problem is
class Image {
   MetaData md;
public:
   const int width,height;
   Image(const char *filename):
     md(readDataFromFile(filename)),
     width(md.width()),height(md.height()) {}
};
However
So the only solution I thought of is along the lines of
class A {
  int stub;
  int init(){/* constructor logic goes here */}
  A():stub(init)/*now initialize all the const fields you wish
  after the constructor ran */{}
};
Is there a better idea? (In Java, you're allowed initializing finals in the constructor).
You could move width and height into one type and move the initialization code into an initialization helper function:
// header:
struct Size { 
    int width, height;
    Size(int w, int h) : width(w), height(h) {}
};
class Image {
    const Size size; // public data members are usually discouraged
public:
    Image(const char *filename);
};
// implementation:
namespace {
    Size init_helper(const char* filename) {
        MetaData md((readDataFromFile(filename)));
        return Size(md.width(), md.height());
    }
}
Image::Image(const char* filename) : size(init_helper(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