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.
class Vehicle
{
int ID;
int partNumber;
public:
//Initialize data members
Vehicle()
{
this->ID = 123;
this->partNumber = 100;
}
//const function
int getId()const
{
return this->ID;
}
};
int main(){
Vehicle obj;
cout<<"Vehicle ID ="<< obj.getId();
}
NOTES:
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.
class Math
{
public:
//const parameter in a function
int Sum(const int n1, const int n2)
{
//n1 =100;//error, you cannot assign to a constant variable
int sum = n1+n2;
return sum;
}
};
int main(){
Math obj;
cout<<"Sum ="<< obj.Sum(2,3);
}
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, rad mutable keyword in C++.
int function(const int a):
Arguments coming to this function cannot be modified.