I am reviewing some code and I ran across some code I am unfamiliar with. After some searching I could not come up of any example of why this is done or the benefit of this declaration.
myClass const * const myPtr = myClass->getPointer();
Is this a declaration of a const pointer or something entirely different?
Best Answer
It means "
myPtr
is aconst
pointer to aconst
myClass
". It means that you can neither modify what the pointer is pointing at through this pointer nor can you make the pointer point somewhere else after it's initialised (by the return value ofmyClass->getPointer()
). So yes, you're basically right, with the addition that it also points to aconst
object (as far as you know; it could really be non-const
underneath).Remember that
const
applies to the item to its left (or if there is no item to its left, the item to its right). The firstconst
makes themyClass
const
(where you can't modify what the pointer points at) and the secondconst
makes the*
const (where you can't modify the pointer itself).