hakuna matata
hakuna matata

Reputation: 3327

C++ const keyword in functions

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

Upvotes: 3

Views: 2056

Answers (1)

juanchopanza
juanchopanza

Reputation: 227370

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.

Upvotes: 6

Related Questions