3

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*?

1
  • 3
    The last one simply means that the function returns a const int* as the result type. As would int const*. Commented Apr 22, 2012 at 7:36

1 Answer 1

6

Your first interpretation is wrong.

int getX() const { ... }

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.

const int* getX() const { ... }

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:

const int* i = someInstange.getX(); // getX() returns const int*
i = someOtherFunction(); // another function returning const int*. OK to reassign i.

So i itself isn't const, but what it points to is:

(*i)++; // ERROR!

if you wanted to return a const pointer to const int you would need something like this:

const int * const getX() {}

The whole issue is further complicated because you can put the first const in different places without changing the meaning. For more information on that, look at this SO question.

Sign up to request clarification or add additional context in comments.

4 Comments

so this just means that the return is const, and i must put it in a const variable?
That's right; you'd get an error if you'd try to assign the result to an int*.
@aizen92 It is a bit subtle. The pointer itself isn't const, so you can assign something else to it. What is const is what the pointer points to. I have edited my answer to reflect that.
@aizen92 I added more info to my answer, and a useful link.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.