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?
We declare a constant pointer. First, we assign the address of variable 'a' to the pointer 'ptr'. Then, we assign the address of variable 'b' to the pointer 'ptr'. Lastly, we try to print the value of the variable pointed by the 'ptr'.
We can create a pointer to a constant in C, which means that the pointer would point to a constant variable (created using const). We can also create a constant pointer to a constant in C, which means that neither the value of the pointer nor the value of the variable pointed to by the pointer would change.
A constant pointer is one that cannot change the address it contains. In other words, we can say that once a constant pointer points to a variable, it cannot point to any other variable. Note: However, these pointers can change the value of the variable they point to but cannot change the address they are holding.
It means "myPtr
is a const
pointer to a const
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 of myClass->getPointer()
). So yes, you're basically right, with the addition that it also points to a const
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 first const
makes the myClass
const
(where you can't modify what the pointer points at) and the second const
makes the *
const (where you can't modify the pointer itself).
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