Is there a good rule for using 'const' in classes and operator overloads in C++? -


i have piece of code this:

class educationalcentre {     string _centrename;     vector<course> _courses;    // courses offered centre     collection<course*, student*, 150> _applicants;  public:     educationalcentre(string name="<name>")     {         _centrename = name;     }      educationalcentre(const educationalcentre& obj)          :_courses(obj._courses), _applicants(obj._applicants)      {         _centrename = obj._centrename;     } }; 

now, in part _applicants(obj._applicants) copy construction header, there's squiggly red line around (obj, hovering error says type incompatibility (const being mentioned).

since don't want change @ stage (this part of exam test) - know why happening.

i tried removing const educationalcentre(const educationalcentre& obj) , indeed solves problem but.. said, rather learn causes instead of removing it.

rule using const use whenever can :)

of course, best practices there exceptions, in general should strive make non-static methods const if don't mutate state of object.

the reason problem collection copy constructor takes non-const reference instance uses source object.

copy constructor can take const or non-const reference argument but, imo, non-const should used when have no choice, rarely. creating object based on object should not change source object, should marked const.

as noted in comment, class being generic has nothing copy ctor taking const reference. indeed, if take @ e.g. std::vector see has copy constructor takes const reference. of methods use in collection copy constructor on argument non-const , why can't make argument const. solution make offending method const, too.

this brings important point: constness viral. if mark method const, other method calls on must const. same calling methods on const objects - can call const methods. if don't beginning, may end in situation making 1 method const results in changing whole chain of other methods, easier give up.

why constness good: bugs caused mutating application state in unexpected ways - ask functional programming fans rave immutability :). const method can't change state of object, eliminates possibility of unexpected changes: e.g. if exception thrown in middle of const method, can sure object not in half-modified state invalidates class invariants.

now, c++ not object oriented language, can change application state in other ways, , can misuse mutable , const_cast trick compiler, using const helps lot in writing correct software , lowering debugging efforts.


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 -