const member function

const member function does not allow to modify nonstatic data member value of an object. Below is the prototype for const function:
<return-value> function() const;
const function with empty definition look like:
<return-value> <className>::function() const {}
From the above you can see that with the const keyword, we can make function a const function.

  • const function makes this pointer as pointer to a const because of this reason, we cannot modify object data i.e. nonstatic data member of an object.
  • const function can be called from const object as well as non-const object but const object cannot call non-const function.
  • There are scenario where we want to modify some data members of an object inside a const function. For such cases, we can use mutable storage specifier.
  • In const function, we can modify static data members. The reason is that const keyword in the const function does not allow to modify non-mutable non-static data members and Static data member does not need object to access.
  • Function overloading is possible based on const type i.e. two functions with same name and same set of parameters but one is const and other is non const. Below is the small program to explain this point.
  • There are two notions attached to const functions.
    a) Bitwise constness
    b) Logical constness
    Bitwise constness: means when const function cannot change any data members (excluding static data members).
    Logical constness: There are some scenario when const function is required and still there is need to change something in the function.
    An example is mentioned in mutable storage specifier.
using namespace std;
class base
unsigned int m_privateMem;
base (int x)
m_privateMem = x;
void display() const
cout << "display const" << endl;
void display()
cout << "display" << endl;

int main()
base b(250);
const base b1 (200);
return 0;

From the above program we can see, const function is called from const object and non-const function is called from non-const function.

Related posts