Members with dynamic pointer and const methods

 

Why can a const method change a class member if it has a dynamic pointer? Is it ok?

class CSomeClass
  {
private:
   int  m_value;
public:
   void change(int newValue)       { m_value = newValue;        }
  };

class CDynamic
  {
private:
   CSomeClass* m_member;
public:
   void        constMethod() const { m_member.change(123);      } // No error
               CDynamic()          { m_member = new CSomeClass; }
              ~CDynamic()          { delete m_member;           }
  };

class CAutomatic
  {
private:
   CSomeClass m_member;
public:
   void       constMethod() const  { m_member.change(123);      } // 'change' - call non-const method for constant object
  };
 
class CSomeClass
  {
private:
   int  m_value;
public:
   void change(int newValue)        { m_value = newValue;        }
  };

class CDynamic
  {
private:
   CSomeClass* m_member;
public:
   void        constMethod1() const { delete m_member;           } // No error
   void        constMethod2() const { m_member = new CSomeClass; } // 'm_member' - member of the constant object cannot be modified
   void        constMethod3() const { m_member = NULL;           } // 'm_member' - member of the constant object cannot be modified
               CDynamic()           { m_member = new CSomeClass; }
              ~CDynamic()           { delete m_member;           }
  };
 
Vladislav Boyko:

Why can a const method change a class member if it has a dynamic pointer? Is it ok?

Yes, that is actually correct, since the member is a pointer and the pointer itself is not altered, there is no change to the object itself.

The change is in the non-const object to where the pointer is pointing to.

 
Dominik Christian Egert #:
Yes, that is actually correct, since the member is a pointer and the pointer itself is not altered, there is no change to the object itself.

The change is in the non-const object to where the pointer is pointing to.

I'm understood, thank you

 
Vladislav Boyko: Why can a const method change a class member if it has a dynamic pointer? Is it ok?
  1. You can't modify any member in a const method.
  2. You are not modding the member, you are deleting what it points to. It is ok, but after the delete it points to nothing.
Reason: