Search code examples
c++pointersmemory-managementprivate-members

C++ protecting a private char * of a class


I understand the differences of inheritance of public, private, protected with respect to class method / property constucts. However, my question is specifically associated with pointers to null terminated strings..

class MyClass
{
   private: 
      char * SomeValue;

   ...
   ...
}

Now, somewhere through processing, the MyClass->SomeValue gets allocated and populated with a string value. No problem. Now, I want some calling source that has an instance of my "MyClass" object created and needs the string value from this. Since C++ can do lots of damage with pointers, and pointers to pointers etc, I want to return the pointer location to the string of chars allocated, but don't want anyone to change values. Is this default controlled inside the compiler and memory management? Its a low risk that anyone would be using this class as its primarily for internal purposes, but just more of my understanding.

Thanks


Solution

  • Typically you would return a const pointer to the chars. There is nothing that can stop someone casting the return value to a non const. But C++ isn't designed to defend against malicious coding.

    class MyClass {
      char* someValue;
    public:
      const char* get_SafeSomeValue() const {
        return someValue;
      }
    };