Sometimes it may be necessary to modify a data member (variable or object in your class) in a const member function. There are two approaches to do that. One is to use the const_cast and the other to use 'mutable'. I use both the approaches in the example below:
//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
//This example shows how to change objects in const member functions
#include<iostream>
using namespace std;
class ABC
{
public:
int func1(int a, int b);
int func2(int a, int b) const;
private:
int x;
mutable int y;
};
int ABC::func1(int a, int b)
{
x = a, y = b;
cout<<"x = "<<x<<" and y = "<<y<<endl;
return 0;
}
int ABC::func2(int a, int b) const
{
//x = a; - COMPILE ERROR because its const
int *temp = const_cast<int*>(&x); //Removing the const
*temp = a; //OK now
y = b; //OK because its defined as mutable
cout<<"x = "<<x<<" and y = "<<y<<endl;
return 0;
}
int main()
{
ABC abc;
abc.func1(3, 7);
abc.func2(20, 40);
return 0;
}
The output is as follows:
No comments:
Post a Comment