use case - Usage of const data member in C++ -


well, know functionality of const data member in c++ class.

what want know is, purpose of introducing const data member in class. why use while writing real software? real-life usage of const data members?

please give me few real life examples reasons.

edit : not asking static const data member. asking real life use cases each object having different const value same data.

you'd use const data member same reason you'd use any const object: value may arbitrarily initialised never changed.

a rule of thumb denote const "by default", can picture plenty of reasons use in class.

class user {     user(const std::string& name)       : name(name)     {}  private:     /**      * user's name invariant lifetime of object.      */     const std::string name; }; 

can leave out const here? yeah, sure. may accidentally change name when didn't mean to. entire purpose of const protect against such accidents.

however, sadly, class not assignable!


Comments

Popular posts from this blog

javascript - Laravel datatable invalid JSON response -

java - Exception in thread "main" org.springframework.context.ApplicationContextException: Unable to start embedded container; -

sql server 2008 - My Sql Code Get An Error Of Msg 245, Level 16, State 1, Line 1 Conversion failed when converting the varchar value '8:45 AM' to data type int -