1

What is the difference between these (in Const manner):

  const int getNum(int &a, int &b) const;

  const int getNum(int &a, int &b);

  int getNum(int &a, int &b) const;

Thank you!

Itzik984
  • 15,968
  • 28
  • 69
  • 107

3 Answers3

3

These are member function declarations, presumably, not regular functions.

const int getNum(int &a, int &b) const;

The leftmost const means that the int being returned from this function is constant. This is a relatively meaningless distinction—sure, the int is constant, but you'll implicitly make a copy of it before using it. This does have an effect on class return types, but it's still not particularly useful.

The rightmost const means that the member function may be called on a constant object, and that the function is not allowed to modify the object. Effectively, the this pointer inside the function will be constant.

const int getNum(int &a, int &b);

The const here has the same meaning as the leftmost const in the first example—the return value is constant.

int getNum(int &a, int &b) const;

The const here has the same meaning as the rightmost const in the first example—the implicit this pointer is constant.

John Calsbeek
  • 35,947
  • 7
  • 94
  • 101
1
const int swap(int &a, int &b);

returns an unchangeable value

  int swap(int &a, int &b) const;

returns changeable value, but inside it no one variable can be changed at runtime.

 const int swap(int &a, int &b) const;

the both

mikithskegg
  • 806
  • 6
  • 10
1

The first and third are const member functions, meaning that they can be called on a const instance, and do not modify any of the instance's fields.

The first and second have return-type const int, which is not very useful, since they return a temporary value, so there's no point in making that value const.

ruakh
  • 175,680
  • 26
  • 273
  • 307