const
functionA 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.
The syntax of the const
function is as follows:
int getValue() const
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 casesconst
member functions have the following use cases:
const
function can be called by either a const
or non-const
object.const
object can call a non-const
function; a const
object 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;}
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.
s
calls getValue()
, but when s
calls getValue1()
, the compiler gives an error, as shown below.s1
calls either getValue()
or getValue1()
.Note: We can uncomment the code in line 25 in the
main
function to check the following compiler error due to the constant object calling a non-constant member function.
Free Resources