Is there a way to create a constant pointer in C++? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 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?

15th Jan 2021, 7:07 PM
Raul Sanchez
Raul Sanchez - avatar
4 Answers
+ 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/
15th Jan 2021, 7:36 PM
Shadow
Shadow - avatar
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++.
15th Jan 2021, 8:57 PM
Mike A
Mike A - avatar
0
Thanks Shadow and Jegix. I am still learning over Pointers and now constant functions in C++. A lot of practice I need to go over. But thank you over the given information. I was also looking over Stackoverflow as well, but that link is much better.
15th Jan 2021, 11:30 PM
Raul Sanchez
Raul Sanchez - avatar
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.
15th Jan 2021, 11:31 PM
Raul Sanchez
Raul Sanchez - avatar