Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Const pointer declaration

Tags:

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?

like image 599
Wesley Avatar asked Mar 19 '12 23:03

Wesley


People also ask

How do you declare a const pointer?

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'.

Can we declare a pointer variable as constant in C?

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.

What does const pointer mean?

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.


1 Answers

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).

like image 110
Seth Carnegie Avatar answered Oct 13 '22 01:10

Seth Carnegie