shinzou
shinzou

Reputation: 6192

How is it possible for a function with an argument int& to handle a variable of a type int**?

How is it possible for a function with an argument int& to handle a variable of type int**?

For example, I have the regular swap function and it works when I pass it variables from a an array of pointers. How is that it doesn't cause a type mismatch error? since swap should receive only int not int**.

void swap(int& a, int& b);
const int SIZE = 6;
int main(){

    int arr[SIZE] = { 1, 2, 3, 4, 5, 6 };
    int*pointers[SIZE];

    int i;
    for (i = 0; i<SIZE; i++)
        pointers[i] = &arr[i];
    for (i = 0; i < SIZE; i++)
        swap(pointers[i], pointers[i + 1]);
}


void swap(int& a, int& b){
    int t;
    t = a;
    a = b;
    b = t;
}

Upvotes: 0

Views: 111

Answers (1)

Barry
Barry

Reputation: 303137

There is already function in the standard called swap, it lives in namespace std and is defined for everything:

// simplification
namespace std {
    template <typename T>
    void swap(T&, T&) { .. }
}

You provide your own version, which doesn't conflict since it's in a different namespace (and isn't a template):

void swap(int&, int&) { .. }

Normally, there would be no contention and what's going on would be obvious:

swap(i1, i2);                      // fine, calls yours
std::swap(c1, c2);                 // fine, calls std::swap<char>
swap(c1, c2);                      // error: can't convert char to int&
swap(pointers[i], pointers[i+1]);  // error: can't convert int* to int&

But somewhere in your code, you have:

using namespace std;

That brings in std::swap into the global namespace - and now your swap just acts as an overload of that one - one which is preferred for int&:

swap(i1, i2);                      // fine, calls yours
swap(c1, c2);                      // fine, calls std::swap<char>
swap(pointers[i], pointers[i+1]);  // fine, calls std::swap<int*>

That's why it works. It's not that somehow you somehow allowed int* to be converted to int& - it's that you're silently calling an entirely different function than the one you thought you were. Moral of the story: avoid using namespace std; - it'll make what your code is doing that much clearer.

Upvotes: 2

Related Questions