The data members of a constant object cannot be changed. If we want some data members to change even when the object is constant, it can be using mutable keyword. The following function shows the use of mutable keyword:

#include<iostream.h>
#include<string.h>
class mobile
{
  char model[20];
  mutable char owner[20];
  int yrofmfg;
  char mobilereg[10];
  
  public: mobile(char *m, char *o, int y, char *r)
  {
    strcpy(model, m);
    strcpy(owner, o);
    yrofmfg = y;
    strcpy(regno, r);
  }
  void changeowner(char *o) const
  {
    strcpy(owner, o);
  }
  void changemodel(char *m)
  {
    strcpy(model,m);
  }
  void display() const
  {
    cout << model << endl 
         << owner << endl 
         << yrofmfg << endl
         << regno;
  }
};
int main (int argc, char *argv[])
{
  const mobile c1("E250", "Gupta", 2006, "KX091EXW342");
  c1.display();
  c1.changeowner("Ghosh");
  c1.display();
}
when the mobile is sold its owner would change but other attributes would remain the same. Since c1 is declared const, none of the data member would change. An exception however has been made in case of owner since its declaration has been preceded by keyword mutable which makes it vulnerable to change.

About our authors: Team EQA

You have viewed 1 page out of 62. Your C++ learning is 0.00% complete. Login to check your learning progress.

#