C++ Const pointer declaration

17,535

Solution 1

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

Solution 2

In some cases, you may see it written like this:

const myClass * const myPtr = myClass->getPointer(); 

The two are equivalent, namely a constant pointer to a constant object. I prefer the syntax as you've shown it because it is easier to understand for newbies when read right-to-left:

Object * const obj;        // read right-to-left:  const pointer to Object
Object const * obj;        // read right-to-left:  pointer to const Object
Object const * const obj;  // read right-to-left:  const pointer to const Object 

Solution 3

The rule is that the const keyword applies to the "word" on the left of it, unless it's the first word on the line, in which case it applies to the "word" on the right of it. So: myClass const * const: myClass <- const, pointer <- const, const pointer to const myClass.

For some reason, in most code (at least the one I've seen), this would be declared as const myClass * const. Why I have no clue, because now you have to take the exception to the "const applies to word on the left, unless it's first word on the line" into account. I.e.: writing lines they way is done in the code you are reviewing is a lot clearer.

Solution 4

This declares a constant pointer to a constant value, returned by calling the member function of a dereference pointer myClass

Solution 5

Seth is on the money. There's some more background you might find useful on Duramecho as well.

Share:
17,535

Related videos on Youtube

Wesley
Author by

Wesley

Programmer at heart

Updated on June 30, 2022

Comments

  • Wesley
    Wesley almost 2 years

    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?

  • linbianxiaocao
    linbianxiaocao over 8 years
    "Remember that const applies to the item to its left (or if there is no item to its left, the item to its right). " - this is the best, simplest, easiest rule of thumb I have seen in classifying const.