2

When coding a header file in C++ with method declarations, what's the difference between:

int getFoo() const;

const int getFoo();

const int getFoo() const;

2 Answers2

2

First one, is for preventing this method changing any member variables of the object. Second one, is for the return type (ie: constant integer) Third one, is mix of both

MIbrah
  • 1,007
  • 1
  • 9
  • 17
0

Your first function operates on a const this pointer (that is; a const object that it can't change (or at least shouldn't)).

Your second function returns a constant integer - which is somewhat nonsensical since you can just assign it to a non-const variable and change it anyway. Besides, why does the function care if you change a POD type or not?

Your third function is just a combination of the first two. A function operating on a const object returning a const value.

Jesper Juhl
  • 30,449
  • 3
  • 47
  • 70