Saturday, May 29, 2010

Const Member Function


If a member function does not alter the value of any data members or we want that member function should not alter the value of any data member then it should be declare as const.

Const function is having only read only access to the data member of the class so it can not write or change the value of data members.

*The qualifier const is appended to the function prototypes both in declaration and definitions. Compiler will generate an error message while the function try to alter the data member.

Example 1

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

void display() const
{
.........
.........
}
};

void main()
{
Test obj;
obj.display();
}

In the above code the function display doesn’t alter the data member so it can be declared as const.

Example 2

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

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

void display()
{
...........
...........
}
};

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

In the above code results an error while compiling because function changeXY() declare as const and try to alter the value of data member x and y.





No comments:

Post a Comment