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.
Vladislav Boyko: Why can a const method change a class member if it has a dynamic pointer? Is it ok?
- You can't modify any member in a const method.
- You are not modding the member, you are deleting what it points to. It is ok, but after the delete it points to nothing.
You are missing trading opportunities:
- Free trading apps
- Over 8,000 signals for copying
- Economic news for exploring financial markets
Registration
Log in
You agree to website policy and terms of use
If you do not have an account, please register
Why can a const method change a class member if it has a dynamic pointer? Is it ok?