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?
tl;dr version: Return a
const Object *.But that’s the whole point of
const-correctness! AnyObjectmethod that doesn’t modify the observable state of the object should be declaredconst. 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
constmethods that then subvert things by casting away theconst-ness ofthis, but that’s always a problem.