4.3. What Are mutable and const?
Consider the following small function:
int sum( const Triangular &trian ) { int beg_pos = trian.beg_pos(); int length = trian.length(); int sum = 0; for ( int ix = 0; ix < length; ++ix ) sum += trian.elem( beg_pos+ix ); return sum; }
trian is a const reference parameter. The compiler, therefore, must guarantee that trian is not modified within sum(). Potentially, trian is modified within any member function that it invokes. To be certain that trian is not modified, the compiler must be sure that beg_pos(), length(), and elem() do not change the class object that invokes them. How does the compiler know that? The class designer must tell the compiler by labeling as const each member function that does not modify ...
Get Essential C++ now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.