Link to home
Start Free TrialLog in
Avatar of Sekhar_ee
Sekhar_ee

asked on

C++

Hi,
In C++ , constatnt member function is not allowed to change the data in the data members. Is there any mechanism , to make constant member function , so that it will behave like an ordinary member function. I mean , like casting ..etc.,
Avatar of Salte
Salte

Yes, you can both use casting but you probably shouldn't.

if you want to change data in a constant member function you really aren't honest, you are telling the user of your class that this function is constant so I won't change any data and then you go ahead and change them anyway. Nasty, nasty.

However, it is possible that the class has members that you want to change - even for constant member functions. This is typically members that doesn't really reflect the value or state of the object but rather are used for book keeping etc, reference counters are a typical example.

Declaring those members to be mutable says that "this member can be modified even by a constant member function" and I would assume that this is by far the best way to go.

class X {
private:
   mutable int a;
   int b;
   static int c;

public:
   static void foo()
   {
    ...can read and write c..
    ... cannot access a or b unless it has a pointer
    ... or reference or have otherwise access to an
    .. instance of X.
   }

   void bar() const
   {
     ..can read and write a and can read b..
     ... cannot modify b though.
     ... can read adn write c also
   }

   void baz()
   {
     ... can read and write a, b and c.
   }
};

My guess is that this is what you really want.

Alf
Doing the nasty

template<v_t> class mrGrinch
{
  private:
  v_t * bar;
  public:
  void foo() const
  {
    v_t * nasty = const_cast(bar);
  //manipulate the pointer like the old dirty you are!
  }

}
ASKER CERTIFIED SOLUTION
Avatar of Salte
Salte

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Sekhar_ee

ASKER

Hi,

Thanks for your solution.

I asked this question keeping const_cast in my mind.