Reputation: 9634
i have a class name X, what is the difference between "const X a" and "X const a"
Upvotes: 4
Views: 1547
Reputation: 1909
If you use simple types (embedded or custom) then that is a matter of taste.
In case of using pointers there is a simple general rule: if const is placed before '*' then the data pointed is constant and otherwise the pointer itself is constant, you can't change its value.
For example:
const int a=1; // 'a' value can't be changed
const int* q; // the data that 'a' point to is constant
int const* q; // the same
int* const p=&a; // the pointer is constant: const is behind '*'
so
int b=2;
p = &b; // error: trying to change constant pointer
Upvotes: 2
Reputation: 490178
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.
Upvotes: 6
Reputation: 355079
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.
Upvotes: 13