c++ - Can I have a const member function that returns *this and works with non-constant objects? -


if understand correctly, member function not supposed modify object should declared const let users know guarantee. now, happens when member function returns reference *this? example:

class c{ public:     c &f() const {return *this;} }; 

inside c::f(), this has type const c*, so, following not compile:

int main() {     c c; // non-constant object!     c.f();     return 0; } 

of course, provide non-const version of c::f() work on non-constant objects:

class c{ public:     const c &f() const;     c &f(); }; 

however, not believe want. note non-constant version not change object, promise users not expressed... missing something?

edit: let me summarize question clarity: f() not modify object on called, declaring c &f(); without making const member misleading. on other hand, want able call f() on non-const objects. how resolve situation?


edit: comes out discussion took place in comments question based on incorrect understanding of constness of function member implies. correct understanding taking away myself is:

a member function returns non-const reference intended allow users change object through returned reference. therefore, though function not change object itself, there should no inclination declare const member!

your problem original function definition:

c &f() const {return *this;} 

here return non-const reference const object, allow changing const object , dangerous, therefore it's forbidden.

if write

const c &f() const {return *this;} 

would callable both const , non-const objects , return const reference.

of course, provide non-const version of c::f() work on non-constant objects. however, not believe want.

probably want. it's way return non-const reference when called on non-const objects , keep const correctness when calling on const objects.


Comments

Popular posts from this blog

c# - Better 64-bit byte array hash -

webrtc - Which ICE candidate am I using and why? -

php - Zend Framework / Skeleton-Application / Composer install issue -