views:

157

answers:

4

i have a class name X, what is the difference between "const X a" and "X const a"

+13  A: 

Nothing.

A const qualifier applies to whatever is immediately to its left. If there is nothing to its left then it applies to whatever is immediately to its right.

James McNellis
But there is a difference between `const int *a`, `int *const a` and `const int *const a`.
Benoit
@Benoit: Yes, there is.
James McNellis
oh, Thanks lot.
Shadow
It is better however to write A const x to be in better harmony with the 'Right Left' rule
Chubsdad
@Chubsdad: Personally I prefer the `A const x` form. But it is hard to argue that one is better than the other (its one of those style things). Now if you have a fantastic reason I would love to hear it (so I can also use it).
Martin York
@Martin York: Me too!. One thing is that it is in harmony with 'Right Left rule'. The other best reason I have so far encountered is from Chapter 1.4 of 'C++ Templates' by David Vandevoorde. It is definitely worth a read about its superiority in context of templates/typedef declarations
Chubsdad
While I certainly understand why some people prefer `T const` over `const T` and I see the potential benefit of the style, I have always found it awkward and haven't gotten used to writing it that way. It's just weird.
James McNellis
+2  A: 

No difference at all.

See: http://www.parashift.com/c++-faq-lite/const-correctness.html

ArunSaha
+5  A: 

In this case, there's no difference at all.

When you have a pointer or a reference, a change that might look almost the same is significant though. Given something like:

T * a;

The position of const (or volatile) relative to the asterisk is significant:

T const * a;
T * const a;

The first one says that a is a pointer to a const T (i.e., you can't modify the T object that a refers to). The second one says that a is a const point to a (non-const) T -- i.e., you can modify what a points at, but you can't modify the pointer itself, so you can't point it at a different object. Of course, you can also do both:

T const * const a;

This means you can't change the pointer itself or the T object it refers to.

Jerry Coffin
+1  A: 
Paul HIQ