Prevent changes to object returned as a pointer

c++, constants

Solution

tl;dr version: Return a `const Object *`.

If the function returns a pointer to a const Object `const Object* getObject() const` the calling function won't be able to use non-const methods of the object (but I want them to be able).

But that's the whole point of `const`-correctness! Any `Object` method that doesn't modify the observable state of the object should be declared `const`. If you're consistent about this, then your problem should disappear. If you're not consistent about this, then the whole thing falls apart (which is probably the cause of your problem!).

Obviously, you can't do anything about `const` methods that then subvert things by casting away the `const`-ness of `this`, but that's always a problem.

Problem

I have a function that returns a pointer to an object. Like this: ``` class SomeClass { public: Object* getObject() const { return &obj; }; private: Object obj; } ``` The problem is that I don't the calling function to change the returned object, it might call functions that operate on it internally, but don't change the obj inside SomeClass... An example might be easier to understand: -If the function returns a pointer to a const Object `const Object* getObject() const` the calling function won't be able to use non-const methods of the object (but I want them to be able). -If I simply return the pointer, the calling functions might change the object: ``` Object* pointer = sclass.getObject(); *pointer = Object(); ``` So the Object inside sclass is now a different object (which I don't want to happen). Is there an workaround?

Original source