Alex Rivera | Logout

Initializing C++ const fields after the constructor

Asked 2010-08-12T06:43:12.340
14

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

  1. It forces me to save MetaData as a field in my object. Which I don't always want.
  2. Sometimes the logic in the constructor is much more complex than a single read (say, error handling can take a few lines)

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).

Edit
Report

2 Answers

4

You should add inline getters for the width and height instead of public const member variables. The compiler will make this solution as fast as the original try.

class Image {
public:
   Image(const char *filename){ // No change here
     MetaData md((readDataFromFile(filename)));
     width = md.width();
     height = md.height();
   }
   int GetWidth() const { return width; }
   int GetHeight() const { return height; }
private:
   int width,height;
};

P.S.: I used to write private things at the end because they are less important for the user of the class.

answered 2010-08-12T07:12:11.580
0

I'd use a static method:

class Image {
public:
    static Image* createFromFile( const std::string& filename ) {
        //read height, width...
        return new Image( width, height ); 
    } 

    //ctor etc...
}
answered 2010-08-12T07:50:48.493

Your Answer