Saturday, May 29, 2010

Mutable Data Member

If a object is declared as const it can read the data member using const member function but can not alter the data member. And if we want to alter the data member using the const object then the data member must be declared as mutable.

Example:

class Test
{
mutable int x;
int y;
public:
Test(int a, int b)
{
x = a;
y = b;
}

void changeXY() const
{
x = 5;
//y = 7; This line produce an error
}

void display() const
{
// Add your own code
}
};

void main()
{
const Test obj(2,3);
obj.changeXY();
obj.display();
}

Const Object

We can create a constant object by using keyword const before object declaration.

class Test
{
.............
.............
};
void main()
{
const Test obj;
}

Const object can not modify the data member and can not call the the non-const data member function. But it can read the data member using const member function.

*Constant object can modify the data member if the data member is declared as mutable.

Example 1:

class Test
{
int x;
int y;
public:
Test()
{
x = y = 2;
}

int calculate() const
{
return (x + y);
}
};

void main()
{
const Test obj;
int a = obj.calculate();
}

The above code we can access value of x and y. Here the object is declared as const. And the object able to access the data member by const member function display().

Example 2:

class Test
{
int x;
int y;
public:
Test()
{
x = y = 2;
}

int Calculate()
{
return (x + y);
}
};

void main()
{
const Test obj;
int a = obj.Calculate();
}

The above code results error because the object is declare as const and it can not call the non-const member function.


Example 3:

class Test
{
int x;
int y;
public:
Test()
{
x = y = 2;
}

void changeXY() const
{
x = 5;
y = 7;
}
};

void main()
{
const Test obj;
obj.changeXY();
}

The above code results an error because the object is declared as const and the const object can not alter the data member.