tags:

views:

99

answers:

3

Possible Duplicate:
what is the difference between const int*, const int * const, int const *

What is the difference between

A const * pa2 = pa1;

and

A * const pa2 = pa1;

(I have some class A for example).

+3  A: 

Read the type from right to left:

A const * pa2 = pa1;

pa2 is a pointer to a read-only A (the object may not be changed through the pointer)

A * const pa2 = pa1;

pa2 is a read-only pointer to A (the pointer may not be changed)

This does not mean that A cannot change (or is actually constant) const is misleading, understand it always as read-only. Other aliased pointers might modify A.

jdehaan
+3  A: 
A const * pa2

This is a non-const pointer to a const A. You can change where the pointer points but you can't change the object pointed to by the pointer.

A * const pa2

This is a const pointer to a non-const A. You can't change where the pointer points but you can change the object pointed to by the pointer.

A const * const pa2

This is a const pointer to a const A. You can't change where the pointer points and you can't change the object pointed to by the pointer.

You may find the "Clockwise/Spiral Rule" helpful when trying to decipher declarations in C and C++.

James McNellis
+1: Very useful link - thanks.
Jonathan Leffler
A: 

It means that the first is a pointer to a const object, which (loosely) means the object can't be change.

The second is a const pointer to an object, which means the pointer itself can not be changed (ie assigned to a different object).

Alan