Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between const declarations in C++

What is the difference between

void func(const Class *myClass)

and

void func(Class *const myClass)

See also:

  • C++ const question
  • How many and which are the uses of "const" in C++?

and probably others...

like image 903
user59688 Avatar asked Jan 28 '09 09:01

user59688


2 Answers

The difference is that for

void func(const Class *myClass)

You point to a class that you cannot change because it is const. But you can modify the myClass pointer (let it point to another class; this don't have any side effects to the caller because it's pointer is copied, it only changes your local the pointer copy) In contrast

void func(Class *const myClass)

Now myClass points to a class that can be modified while you cannot change the parameter.

like image 60
mmmmmmmm Avatar answered Oct 29 '22 03:10

mmmmmmmm


In the first one you're declaring a function that accepts a pointer to a constant Class object. You cannot modify the object inside the function. In the second one you're declaring a function that accepts a constant pointer to a non constant Class object. You can modify the object through the pointer, but cannot modify the pointer value itself.

I always keep in mind this easy rule: const always applies on the thing at the immediate left of it, if this thing doesn't exists, it applies to the thing on the immediate right.

Also take a look to this question which I asked a week ago, it points to some very useful links to understand const correctness.

like image 26
tunnuz Avatar answered Oct 29 '22 04:10

tunnuz