Skip to main content

18.1) Const Methods


Methods that don’t modify the object in any way should always be declared as const. Declaring them as such means that they can be called on const instances of your class. If you don't declare a method as const then subsequently create a const instance in a program and attempt to call the method on it, you will get a compiler error.

The const declaration should be used in both the header and implementation files. Thus, the header file defining the Rectangle class changes to this:

class Rectangle
{
  public:
    Rectangle(int, int, int, int);
    int get_x() const;
    int get_y() const;
  ...
};

And the method implementations now look like this:

int Rectangle::get_x() const
{
  return corner_x;
}
int Rectangle::get_y() const
{
  return corner_y;
}
...