Const Objects and const Member Functions - C++ Class

C++ examples for Class:object

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
{
  // ...
  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
{
private:
  double length;
  double width;
  double height;
  mutable std::string name;                 // Name of a pool

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

Related Tutorials