c++ - a const member function, returning a pointer to a non const member variable, why would it be good? -
i work in large collaboration (of non-professional programmers, being 1 of them). regularly see examples of following
void t::dochanges(i i); // make changes internal structure of t (non-const) v t::getvalue(); class { private: t* fmember; public: a(); t* getmember() const {return fmember;} }
, use-case be
a a; i; a->getmember()->dochanges(i); v v = a->getmember()->getvalue();
this practice violates tenant drilled me when took programming courses, i.e. const refers not bitwise structure of class instance, internal logical structure. under philosophy, member function should take following forms:
t* getmember() {return fmember;} const t* getmember() const {return fmember;}
i have heard people think const should refer members, speaking strictly using c++ terminology. how/why argue type of practice?
making member function gives indication users of function not modify any class members.
returned member may or maynot const
making member function const gives users of class clear indication of behavior of function.
Comments
Post a Comment