What is purpose of const in this declaration “void function()const”?

const member function, “void function() const” is explained with an example. Need to focus on especially mutable keywords and pointer member in this case.

In interview, explaining the concept with example makes answer impressive.

Answer:

Point -1

  • Inside the “function()const” class members can’t be modified.
  • Only class members declared with “mutable” keyword can be modified.
Point -2

  • Normal object can call both const and non-const functions().
  • Const object can call only const function();
NOTES:

It is really important to note that if we have a class variable as a pointer. In constant function as declared above a pointer address cannot be modified but, the value pointed by that pointer can be modified. Notice the function body of func3().

 

With object reference of a class as mentioned below it is OK to modify member variable.

void func4(A& obj) const    {

obj.a = 42; // OK! obj is a reference to non-const

}