Constant Argument Function in C++

In C++, an argument to a function can be declared as unit as constant. The qualifier const tells the compiler that the function should not modify the argument.

The compiler will generate an error when this condition is violated. This type of declaration is significant only when we pass arguments by reference or pointers.

A function becomes const when the const keyword is used in the function’s declaration. The idea of const functions is not to allow them to modify the object on which they are called. It is recommended the practice to make as many functions const as possible so that accidental changes to objects are avoided.

Syntax:

int strlen(const char *p);
int length(const string &s);

Example:

#include<iostream> 
using namespace std; 
class Test 
{ 
	int value; 
public: 
	Test(int v = 0) 
	{
		value = v;
	} 
// We get compiler error if we add a line like "value = 100;" 
	// in this function. 
	int getValue() const 
	{
		return value;
	} 
}; 

int main() { 
	Test t(20); 
	cout<<t.getValue(); 
	return 0; 
} 

Output:

20

When a function is declared as const, it can be called on any type of object. Non-const functions can only be called by non-const objects.

Related posts