c++ - initializing const fields in the constructor -
const fields in c++ must initialized in initialization list, makes non trivial computation of interdependent values constructor parameters.
what is(are) best way(s) translate, example, piece of java code c++ ?
public class someobject { private final string some_string; private final int some_int; public someobject(final string input_filename){ somereader reader = new somereader(input_filename); some_string = reader.getstring(); some_int = reader.getint(); reader.close(); } }
i thought of encapsulating sub-object in someobject, shifting problem; or constructing object using static method:
class someobject { private: const std::string some_string; const int some_int; public: static someobject unserialize(const char * input_filename){ somereader reader = new somereader(input_filename); string str = reader.get_string(); int = reader.get_int(); reader.close(); someobject obj(str, i); return obj; }; someobject(const std::string str, const int i) : some_string(str), some_int(i) {}; }
is there better solution ?
thank you.
this great application c++11 constructor delegation:
class someobject { private: const std::string some_string; const int some_int; public: // "real" constructor someobject someobject(std::string str, const int i) : some_string{std::move(str)}, some_int{i} {} // deserialize somereader (delegates primary constructor) someobject(somereader& reader) : someobject{reader.get_string(), reader.get_int()} {} // deserialize somereader (accepts rvalues, // delegates lvalue constructor) someobject(somereader&& reader) : someobject{reader} {} // deserialize named file (delegates somereader&& constructor) someobject(const char* input_filename) : someobject{somereader{input_filename}} {} };
Comments
Post a Comment