Skip to Main Content
C++ In a Nutshell
book

C++ In a Nutshell

by Ray Lischner
May 2003
Intermediate to advanced content levelIntermediate to advanced
808 pages
32h 24m
English
O'Reilly Media, Inc.
Content preview from C++ In a Nutshell

Name

mutable specifier — Mutable data member specifier

Synopsis

               storage-class-specifier := mutable

The mutable specifier can be used with the declaration of a data member. Using it means that the member can be modified even if the containing object is const.

Example

// Represent a point in Cartesian coordinates. If the user requests polar
// coordinates, compute and cache the polar coordinates. If the Cartesian
// coordinates change, the polar coordinates must be recomputed. The polar
// coordinates are computed only if they are needed.
struct point {
  double angle(  ) const {
    if (! has_angle_) {
      angle_ = tan2(y, x);
      has_angle_ = true;
    }
    return angle_;
  }
  void x(double x) { x_ = x; has_angle_ = has_arg_ = false; }
  ...
private:
  double x_, y_;mutable double angle_, arg_;
  mutable bool has_angle_, has_arg_;
};
int main(  )
{
  const point pt(1, 2);
  std::cout << pt.angle(  );
}

See Also

class, const, declaration, type, Chapter 6

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

C++ High Performance

C++ High Performance

Viktor Sehr, Björn Andrist
Optimized C++

Optimized C++

Kurt Guntheroth
Mastering C++ Programming

Mastering C++ Programming

Jeganathan Swaminathan

Publisher Resources

ISBN: 059600298XSupplemental ContentErrata Page