简体   繁体   中英

Function overloading with default parameter in c++

My program is:

class base {
    int a, b;
public:
    int add(int a, int b) {
        return a + b;
    }
    int add(int a, int b, int c=0 ){
        return a + b + c;
    }
};

int main() {

    base b;
    b.add(10, 20);//compilation error
    return 0;
}

I know there is ambiguity arise. But I want to know how a compiler works for a default argument with function overloading. Because if I'm not calling this function or call add(10,20,0) it works fine.

or

for function overloading it is treated as add(int,int),add(int,int, int)because it has 2 different function signature but what logic behind that please explain in detail.

Here is how it(overload resolution) works:

16.3.2.1 From the set of candidate functions constructed for a given context (16.3.1), a set of viable functions is chosen, from which the best function will be selected by comparing argument conversion sequences and associated constraints (17.4.2) for the best fit (16.3.3).

16.3.2.2 First, to be a viable function, a candidate function shall have enough parameters to agree in number with the arguments in the list. [...] A candidate function having more than m parameters is viable only if the (m+1)-st parameter has a default argument (11.3.6). For the purposes of overload resolution, the parameter list is truncated on the right, so that there are exactly m parameters.

So basically, they have identical signature during overload resolution.

You have two functions named add . One takes two arguments, and the other takes three arguments. The second function's signature is add(int, int, int) , always. It does not have two signatures.

It's just that if you don't give it that third argument yourself, it's filled in for you.

Of course, this can only happen when overload resolution has already found add(int, int, int) ; as you've discovered, in this particular case, it's impossible for the compiler to guess which add you wanted, but if not for the ambiguity then it would be simple. The default argument is basically syntactic sugar, and has no effect on the internals of the function, on its signature, or on its mangled symbol name.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM