C++ Function overloading using const parameters

95 Views Asked by At
#include <iostream>

using std::cout;

class CheckConst
{
public:
    void func(int* p)
    {
        cout << "func called";
    }

    void func(const int* p)
    {
        cout << "const func called";
    }
};

int main()
{
    int* p = nullptr;
    CheckConst obj;
    obj.func(p);
}

Above function overloading works fine. But why is the complier not complaining, both the function overloads are valid for function call for obj.func(p). If I remove either one of the function from the class, the code still works.

How is the complier distinguishing which one to call?

2

There are 2 best solutions below

0
user12002570 On BEST ANSWER

why is the complier not complaining

Because the first function func(int* p) is an exact match via identity conversion while the second function func(const int* p) requires a qualification conversion(aka conversion to const).

Thus, second function is worst match than the first, for the argument p.


Basically, the first function doesn't require any conversion(aka identity conversion) for its argument p.

From over.ics.rank:

Standard conversion sequence S1 is a better conversion sequence than standard conversion sequence S2 if

  • S1 and S2 differ only in their qualification conversion ([conv.qual]) and yield similar types T1 and T2, respectively, where T1 can be converted to T2 by a qualification conversion.
0
J Chen On

The compiler picks the func overload with the least required argument conversion. For int* p = nullptr;, it chooses func(int*) because it's a direct match without conversion. Since nullptr is valid for both int* and const int*, removing either overload still leads to unambiguous function selection.

The key to understanding how the compiler makes its choice lies in the type of the argument p and the concept of "qualification conversion." In the context of function overloading, C++ prefers to match functions with the least amount of conversion required for the arguments.