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

5
  • Is this what you're asking? stackoverflow.com/q/3682049/2065121 Commented Jun 11, 2013 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 Commented Jun 11, 2013 at 10:33
  • Related post from yesterday concerning the top-level const qualifiers. Commented Jun 11, 2013 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 Commented Jun 11, 2013 at 10:48
  • @AbhishekDixit stackoverflow.com/questions/3141087/… Commented Jun 11, 2013 at 11:06

1 Answer 1

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.

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

1 Comment

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 ?

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.