Define factory class in C++ -


i have "like factory" class:

class specialreader { private:     handle specialfile;     specialreader(handle specialfile); public:     static specialreader create(tchar* filename);     ~specialreader(); }  //where   specialreader::create(tchar* filename) { // ... // ...  return specialreader(inputfile); } 

i want define object in program body this:

specialreader myreader; 

but not:

specialreader myreader = specialreader::create(anyfile); 

if try define object in first case i've got compiler error:

error c2512: 'specialreader' : no appropriate default constructor available.  

how define class right?

you can use smart pointer so, simplest choice using std::unique_ptr<specialreader> , transfer ownership of instance caller:

class specialreader { private:     handle specialfile;     specialreader(handle specialfile);         public:     static std::unique_ptr<specialreader> create(tchar* filename);         // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^     ~specialreader(); }  std::unique_ptr<specialreader> specialreader::create(tchar* filename) {     // ...     return std::unique_ptr<specialreader>(new specialreader(inputfile)); } 

to delayed creation can write follows. syntax different op, achieves same:

std::unique_ptr<specialreader> myreader;  // ....  myreader = specialreader::create(filename); 

as comments, want handle failure within create() factory function, can return empty std::unique_ptr<specialreader>, , let client check it:

std::unique_ptr<specialreader> specialreader::create(tchar* filename) {     try {         // ...         return std::unique_ptr<specialreader>(new specialreader(inputfile));     }     catch(...) {         // ignore exceptions     }     return std::unique_ptr<specialreader>(); } 

std::unique_ptr<specialreader> myreader; myreader = specialreader::create(filename); if(!myreader.get()) {     // error handling, create() couldn't create instance of specialreader } 

Comments

Popular posts from this blog

php - failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request -

java - How to filter a backspace keyboard input -

java - Show Soft Keyboard when EditText Appears -