+ 3
Is there a way to create a constant pointer in C++?
https://code.sololearn.com/chkOWE7Hsxy4/?ref=app This is my example above. I am just learning and practicing with Pointers. Now I am in a section of C++ that is using pointers for objects in a class. I learned how to use a pointer. But I am now researching over a constant pointer. I don't know how to create one properly. Can someone help?
4 Antworten
+ 8
There are three possibilities, so it depends on what you want:
1. Pointer to a constant
const MyClass * p
MyClass const * p
This declaration means you can affect and change the pointer itself, e.g. increment it, but you can not change the object it points to.
2. Constant pointer
MyClass * const p
Here the opposite happens, i.e. you can change the object referred to by the pointer, but the pointer is immutable. The usual rules for constant variables apply.
3. Constant pointer to a constant
const MyClass * const p
MyClass const * const p
Such a pointer shares the attributes by the types mentioned above, i.e. both the pointer and its object are immutable.
But you also could have just looked this up, e.g. here:
https://stackoverflow.com/questions/21476869/constant-pointer-vs-pointer-to-constant/21476937
https://www.learncpp.com/cpp-tutorial/pointers-and-const/
0
Shadow
"Such a pointer shares the attributes by the types mentioned above, i.e. both the pointer and its object are immutable."
I assume that you mean from the perspective of the pointer the object is immutable. Since immutability is not a concept in C or C++.
0
Shadow
Also the one I was going for was the 1st one. The pointer to a constant.
Now I realize there are other ways to use pointers. I wanted to see how to manipulate the information.