I am trying to use a return type of const MyClass * const
. However, I get a warning:
Warning: #815-D: type qualifier on return type is meaningless.
Is this not a valid type? I want a pointer than cannot be changed, and I want the thing it points to to not be changed either.
The pointer itself has value type, so it doesn't make sense to make it const. What the caller function does with the returned value can't be restricted by the called function. This is akin to trying to define something like:
const int getInt();
getInt(), in this case, just returns an int value (not a reference). It goes to a register, then the caller function receives it and does whatever it wants with it.
I agree with Juliano's answer, you want the constness of the pointer to be at the call site.
A better way to do what you are looking for is to have your function return a const reference to the object:
const MyClass& getMyClass()
{
return myClass;
}
By definition references can't be modified, so you'd be better off.
Of course this won't work if your function is attempting to create a MyClass object. In that case you can just move the extra const to the call site.
// function definition
const MyClass* createMyClass()
{
return new MyClass("I Love C++");
}
// use of a const pointer to a MyClass which is const
const MyClass* const myClassInstance = creatMyClass();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With