const member function, “void function() const” is explained with an example. Need to focus on especially mutable keywords and pointer member in this case.
In interview, explaining the concept with example makes answer impressive.
Answer:
Point -1
- Inside the “function()const” class members can’t be modified.
- Only class members declared with “mutable” keyword can be modified.
#include
using namespace std;
class A{
private:
int a;
mutable int b;
int *ptr;
public:
void func1(){
cout<<"Normal function():func1()\n";
}
void func2()const
{
a=2; //Error :class variable, can't be modified. Error : l-value specifies const object.
b=3; // OK.
cout<<"const function():func2()\n";
}
void func3()const
{
ptr =10;//Error : cannot convert from 'int' to 'int* const'
*ptr=10;
cout<<"const function():func3()\n";
}
};
int main(){
A ob;
ob.func2();
return 0;
}
Point -2
- Normal object can call both const and non-const functions().
- Const object can call only const function();
int main(){
A ob1; // Normal object can call both const and non-const function() of a class.
ob1.func1();//OK
ob1.func2();//OK
const A ob2;//Const object can call only const function.
ob2.func1();//Error.- cannot convert 'this' pointer from 'const A' to 'A&'
ob2.func2();//OK
return 0;
}
NOTES:
It is really important to note that if we have a class variable as a pointer. In constant function as declared above a pointer address cannot be modified but, the value pointed by that pointer can be modified. Notice the function body of func3().
With object reference of a class as mentioned below it is OK to modify member variable.
void func4(A& obj) const {
obj.a = 42; // OK! obj is a reference to non-const
}