Thursday, May 29, 2008

What is need for Mutable?

  • Data members cannot be changed in const objects.
  • In some scenarios this is required and mutable keyword provides the solution.

Demonstrate the usage of mutable keyword

#include <iostream>
using namespace std;

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

       void SetX(int a) const
       {
           x=a;
       }

       void SetY(int b) const
       {
              /* Compilation Error
               y=b;
               Error E2024 mutable.cpp 21: Cannot modify a const object in function MyClass::SetY(int) const
               */
       }
};

int main() {
 
   // Create a const object
   const MyClass obj(5,5);

   obj.SetX(10);

   return 0;
}

4 comments :

  1. WOW! This is the best C++ tutorial all over the Internet! Thanks a lot for your efforts! You help me so much!

    ReplyDelete
  2. nice example...quite easy to understand...Thanks

    ReplyDelete
  3. Totally agreed!
    this is the greatest C++ tutorial site over the internet.thankx guyz.keep it up!

    ReplyDelete
  4. all the topics are to the point with out adding any complexity. Thanks for sharing. Really been helpful.
    Narasimha Rao

    ReplyDelete

Contact Form

Name

Email *

Message *

Back to Top