Describe constant member function in C++ with Example

(Last Updated On: February 26, 2019)

Answer: Constant member function in C++ of a class is the function that prevents modification of any member data of a class in C++ program. To make a function constant in a class, we use “const” keyword in function declaration. For example, “void foo() const ” .

In below source code example, we have declare the function getID() as a const function.  Inside this function no Vehicle class data members e.g. int ID and int partNumber can be modified.




C++ const function parameter

const keyword used in function parameter stops modifying values that are coming to the function as an argument. For example, in below program, if we try to modify the argument n1 inside a function Sum(), compiler will throw an error.



Difference between int function()const and int function(const int a):

int function() const:

No any member data of a class can be modified. If you want to know how a data member of a class is allowed to be modified inside a constant member function in c++ program, read mutable keyword in c++.

int function(const int a):

Arguments coming to this function cannot be modified.