2.3 const functions

In addition to const data members, a class can also contain const functions/methods. A function that is declared const means that it does not alter the object that provides the context of its execution. Let us observe the following code:

class X
{
    int i;
  public:
    void set(int i);
    int get(void) const;
};

void X::set(int i)
{
  this->i = i;
}

int X::get(void) const
{
  return i;
}

In this example, set cannot be a const method because it alters a data member of the object that provides the context of its execution. However, get is a const method because it only read a data member of the object that provides the context.



Copyright © 2006-09-19 by Tak Auyeung