1

Consider this

#include <iostream>

class A
{
public:
  void fun(int x) const
  {
    std::cout<<"int x"<<std::endl;
  }
  void fun(const int x)
  {
    std::cout<<"const int x"<<std::endl;
  }
  void fun(int &x)
  {
    std::cout<<"int &x"<<std::endl;
  }
  void fun(const int &x)
  {
    std::cout<<"const int &x"<<std::endl;
  }
};

int main()
{
  A obj;
  int a = 10;
  const int b = 10;
  int& ref = a;
  const int& ref1 = b;
  obj.fun(a);
  obj.fun(b);
  obj.fun(ref);
  obj.fun(ref1);
  return 0;
}
  1. Compiling this get ambiguities but none of them says its due to fun(const int x) but removing this makes code getting compiled correctly

  2. What difference does it make when we make a argument const ex- fun(const int& x) and a function itself const ex - fun(int x) const while overload resolution

There are some more doubts trying various combinations, so any generic answer explaining the role of const while overload resolution is welcome

  • Is this what you're asking? http://stackoverflow.com/q/3682049/2065121 – Roger Rowland Jun 11 '13 at 10:26
  • thanks it answers the first point to an extent. But are there any generic rules ? for ex if we remove const from fun(int x) const then its ambiguous with fun(const int&) otherwise not – Abhishek Dixit Jun 11 '13 at 10:33
  • [Related post from yesterday](http://stackoverflow.com/questions/17033074/overloading-on-const-and-volatile-why-does-it-work-by-reference) concerning the top-level `const` qualifiers. – juanchopanza Jun 11 '13 at 10:45
  • the issue left is why fun(int x) const is not ambiguous with fun(const int& x) while fun(int x) is – Abhishek Dixit Jun 11 '13 at 10:48
  • @AbhishekDixit http://stackoverflow.com/questions/3141087/what-is-meant-with-const-at-end-of-function-declaration – Suvarna Pattayil Jun 11 '13 at 11:06

1 Answers1

2

Top level const is ignored on a declaration, so fun(const int x) is same as fun(int x).

Certainly it will conflict with the ref versions and hardly makes any sense. If you hunt for rvalues add fun(int &&x), though its normally used with user defined types

The const after the () qualifies the object instance -- the this pointer. Seleced when you would use const A obj.

Balog Pal
  • 16,195
  • 2
  • 23
  • 37
  • function qualified by const can be called from non-const object also. I am assuming non-const version is preferred in this case and overload resolution is done on the basis of implicit type of 'this'. Am I right ? – Abhishek Dixit Jun 11 '13 at 11:30