O'Reilly logo

Essential C++ by Stanley B. Lippman

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required