C++ const Objects and const Member Functions

Introduction

You can ask a method which doesn't alter the object by const keyword.

First, you specify the function as const in the class definition:

class Pool/*www.j a v  a  2s .  c o m*/
{
  // ...
  double volume() const;                            // Function to calculate the volume of a pool
};


double Pool::volume() const
{
  return length*width*height;
}

To allow particular class members to be modifiable even for a const object.

You can do this by specifying such members as mutable. For example:

class Pool/*w  w w  .j  a v  a  2 s .  c o  m*/
{
private:
  double length;
  double width;
  double height;
  mutable std::string name;                 // Name of a pool

  // Rest of the class definition...
};



PreviousNext

Related