Overloaded functions in C ++

Are these features advanced features?

void f(int a, int b) {} void f(int& a, int& b) {} void f(int* a, int* b) {} void f(const int a, const int b) {} 

Or do overload functions only occur when the number or type of arguments differs?

+4
source share
2 answers

Number 1, 2, 3. Number 4, updated number 1.

You see, higher qualifier-constructors do not affect the declaration of a function. They change the way you use them in a function definition, but it's still the same function

 void f(int); void f(const int); //redeclares void f(const int x) //same as above { x = 4; //error, x is const } 

This, on the other hand, is wonderful.

 void f(const int); void f(int x) //same as above { x = 4; //OK Now } 

Note that top-level constants do not participate in overload resolution. For instance.

 void f(int & x) void f(const int & x) //another function, overloading the previous one 

And finally, you ask

Only overload functions are executed only when the number or type of arguments is different?

Yes, that’s correct, but int , int* and int& are different types. Of course, in case 1 or 3, in most cases these will be ambiguous calls, but in some cases the compiler can determine what you mean. for instance

 void f(int); void f(int&); f(3)//calls f(int) int x = 3; f(x); //ambiguous call; 
+7
source

Although 1st and 2nd will cause ambiguity with lvalues, they are nonetheless overloaded. And 4th β€” redefinition of the 1st:

http://ideone.com/lRFQi

+3
source

Source: https://habr.com/ru/post/1343956/


All Articles