c++ - Best approach to interface (abstract classes) design? -


i've searched on topic couldn't find relevant answer...

suppose have abstract class declared :

class abstract{      virtual interface* createhandle() = 0;      virtual ~abstract() = 0; }; 

basically, abstract class provides unique function returns implementation of class interface (also abstract class).

i'm wondering how can error handled such design. if createhandle() encounters error , cannot return pointer implementation of interface, what's best way handle , notify ?

the first thing came mind return null pointer, , check in calling code if returned pointer null. work, find quite poorly designed, because interface (namely abstract) never implies createhandle() can return null pointer, or will return null pointer signal error (and find quite bad fact of leaving comment saying "should return null if error").

then, thought of carrying information in interface pointer. is, adding 2 public non-virtual function class set/get sort of error code. don't @ has nothing interface class, implementation of createhandle() interface has no knowledge (i.e. having member variable stores errors related code using class, feels wrong in opinion, though may wrong).

i wonder then, elegant way of specifying how function behave in case of error (in way independent of implementation, quite other way around in fact : forcing implementations deal error way it's been specified).

you can throw exception if case exceptional must handled (though can not enforce this, @ least mark situation exceptional). otherwise returning nullptr totally ok.

for example if want read file potentially may not exist - it's not program error, expected situation, returning nullptr filereader example makes sence.

also indicate nullptr valid think , enforce checking may return boost::optional or own optional class may contain error code.


Comments

Popular posts from this blog

jquery - How can I dynamically add a browser tab? -

node.js - Getting the socket id,user id pair of a logged in user(s) -

keyboard - C++ GetAsyncKeyState alternative -