Abhishek Dixit
Abhishek Dixit

Reputation: 127

Function overloading resolution with const

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

Upvotes: 1

Views: 218

Answers (1)

Balog Pal
Balog Pal

Reputation: 17163

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.

Upvotes: 2

Related Questions