Saturday, May 29, 2010

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.






No comments:

Post a Comment