Constant Member Functions in C++

Estudies4you

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
Constant Member Functions in C++,Discuss about constant member functions in c++,define class in c++,syntax for class,class syntax,data abstraction in c++,data hiding in c++,what is object,difference between class and object,how to declare a object to class,what is scope of class in c++,types of scopes in c++,estudies4you,pointers in c++,static members of a class in c++,Static Member Function in c++, constructor and destructors in c++,difference between constructor and destructor,define constructor,define destructor,static member functions,data abstraction definition,short notes on data abstraction,types of abstraction in c++,what is ADT in c++,abstract data type in c++,information hiding in c++,
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.
     


To Top