1

I cannot figure out why I am getting the error "reference to 'distance' is ambiguous".
I have passed class object as an argument in friend function.

#include <iostream>
using namespace std;

class distance {
    int meters = 0;
public:
    distance() {}
    void displaydata() {
        cout << "Meters Value:" << meters;
    }
    //Prototype
    friend void addvalue(distance &d);
};

void addvalue(distance &d) {
    d.meters += 5;
}

int main() {
    distance d1; // meters = 0
    d1.displaydata(); // 0
    // The friend function call
    addvalue(d1); // pass by reference
    d1.displaydata();
}
Deduplicator
  • 44,692
  • 7
  • 66
  • 118
  • 5
    It's because you are `using namespace std;`. Don't to that, [it's a bad practice to do so](https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice). – Fureeish Sep 21 '20 at 19:20
  • There already is a `std::distance` function. Since you are including all `std` symbols into your namespace, the compiler can get confused as to which `distance` symbol you are referring to. Try prefixing *your* `distance` with `::` as in `::distance d1;` – Thomas Matthews Sep 21 '20 at 20:28

1 Answers1

1

If you remove the using namespace std; and change cout to std::cout, then your code compiles w/o error.

Discovering the source of the ambiguity is left as an exercise to the reader

Marshall Clow
  • 15,972
  • 2
  • 29
  • 45