CONSTANT MEMBER FUNCTIONS
Q18. Discuss about constant member functions.
Answer:
The member functions that are succeeded by a keyword const are called as constant member functions. The const keyword is succeeded to constant member function declaration and at the as time definition . A compiler error is raised when a const member function is modified .
Program
#include<iostream.h>
#include<conio.h>
class Sample
{
int val;
public:
Sample(int n = 0)
{
val =n;
}
int getValue() const
{
return val;
}
};
int main()
{
const Sample s(28);
Sample s1(8);
cout << "The value
using object s : " << s.getValue();
cout << "\nThe value
using object s1 : " << s1.getValue();
return 0;
}
Output
The above program calculates difference of two integers using const member function and the result is displayed.
A class named as sample is declared that contains a private variable val and const member function getValue( ). The const member function does not allow to modify the function.
In const member, subtraction operation is performed. For these functions, CPU registers are used to display the output on screen. Since, when the result is not assigned to any variable, it is stored in accumulator (Ax) by default.