I understand when using it as follows:
int getX() const {...}
means that this function will not modify any of the variables used in its body. But what I didnt undertsnad is using const in 2 places, like the following:
const int* getX () const {...}
what’s the use of putting the const keyword before the int*?
Your first interpretation is wrong.
is a member function, and it cannot modify any data members or call any non-const for a given instance of the class that has that function.
returns a
const int*, so it limits what you can assign to using it. It is a non-const pointer to const int, so you cannot modify the int it points to, but you can modify the pointer itself. For example:So
iitself isn’tconst, but what it points to is:if you wanted to return a const pointer to const int you would need something like this:
The whole issue is further complicated because you can put the first
constin different places without changing the meaning. For more information on that, look at this SO question.