7.5. const member functions

We have previously mentioned uses for const, and classes add another situation where the const keyword can be used.

An object can be created with the const cv qualifier, just like any other type:

const int x = 3;

const Fibonacci foo = {5, 8, 13};

When created const, then no changes are allowed to the object. It is OK to call a non-modifying member function.

How does the compiler know that a function is a non-modifying member function? When the function is declared as const.

Create a const member function by inserting the const keyword after the parameter list and before the function body:

bool verbose() const {
  return true;
}

Here const tells the compiler this function will not change the object state.

It is a promise. If a const function attempts to change any class member, then a compile error results.

Note

Only class member functions can be marked const.

Attempting to mark a free function as const is a compile error.


More to Explore

You have attempted of activities on this page