What are const functions in C++?
The const function
A function declared with the const keyword is a constant function. Constant functions are popular due to their ability to prevent accidental changes to the object’s value.
Syntax
The syntax of the const function is as follows:
int getValue() const
Code
Following is the sample code for the const function.
In the code below, getValue() is the constant function, s is a const object, and s1 is a non- const object:
#include<iostream>using namespace std;class sample {int val;public:sample(int x = 0) {val = x;}int getValue() const {return val;}};int main() {const sample s(20);sample s1(2);cout << "The value using object d : " << s.getValue();cout << "\nThe value using object d1 : " << s1.getValue();return 0;}
const function use cases
const member functions have the following use cases:
- A
constfunction can be called by either aconstor non-constobject. - Only a non-
constobject can call a non-constfunction; aconstobject cannot call it.
#include<iostream>using namespace std;class sample {int val;public:sample(int x = 0) {val = x;}int getValue() const {return val;}int getValue1() {return val;}};int main() {const sample s(20);sample s1(2);cout << "The const function called by const object s : " << s.getValue();cout << "\nThe const function called by non-const object s1 : " << s1.getValue();cout << "\nThe non-const function called by non-const object s1 : " << s1.getValue1();//cout << "\nThe non-const function called by const object s : " << s.getValue1(); //Gives compiler error becausereturn 0;}
Explanation
In the code above, the function getvalue() is a const member function, whereas getvalue1() is a non-const member function. Moreover, s is a const, whereas s1 is a non-const object.
- There is no error when
scallsgetValue(), but whenscallsgetValue1(), the compiler gives an error, as shown below. - There is no error when
s1calls eithergetValue()orgetValue1().
Note: We can uncomment the code in line 25 in the
mainfunction to check the following compiler error due to the constant object calling a non-constant member function.
Free Resources