Const Functions in C++

The Const member functions are used to prevent modifications of class data members within it.Likewise,the const parameters are used to prevent modification of data collected by them.

class sample
{
     int i;
     public:
               int fun() const
               {
                      i=82;   //error
                      return i;
               }
               void fun1(const int &ii)
               {
                      ii=8;    //error
               }
};
void main()
{
      sample s;
      int p=9;
      p=s.fun();
      s.fun1(p);
}

Here fun() is a const member function.Hence ,compiler flashes an error when we try to modify the data member i.Similarly,the function fun1() cannot modify the value of ii as ii is declared as const.

No comments:

Post a Comment