Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overloaded functions in C++

Tags:

c++

Are this functions overlaoded functions ?

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 overloading functions occurs only when the number or type of arguments differ ?

like image 737
Adrian Avatar asked Dec 27 '22 23:12

Adrian


2 Answers

Number 1, 2, 3 are. Number 4 redeclared number 1.

You see, top-level const-qualifiers don't affect the function declaration. They alter the way in which you use them inside 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 fine

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

Note that non-top-level consts do participate in overload resolution. E.g.

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

And finally, you are asking

Or overloading functions occurs only when the number or type of arguments differ ?

Yes, that's right, but int , int*, and int& are different types. Of course, in case of 1 or 3, in most cases it will be ambiguous calls, but in some cases the compiler can tell which one you mean. For example

void f(int);
void f(int&);
f(3)//calls f(int)
int x = 3;
f(x); //ambiguous call;
like image 69
Armen Tsirunyan Avatar answered Dec 30 '22 13:12

Armen Tsirunyan


Although 1st, and 2nd would cause ambiguity with lvalues, nevertheless they're overload. And 4th is redefinition of 1st:

http://ideone.com/lRFQi

like image 39
Nawaz Avatar answered Dec 30 '22 12:12

Nawaz