Hey guys,

I have a class with a friend function and a member function with the same name. Calling the friend function from the member function gives me an error: it looks for <classname>::<function> while the friend function is of course simply <function>.

In this case, MinGW GCC says:

\Code\RationalNumber\rational.cpp | In member function `long long unsigned int rational::gcd() const':
\Code\RationalNumber\rational.cpp | error: no matching function for call to `rational::gcd(const long long unsigned int&, const long long unsigned int&) const'
\Code\RationalNumber\rational.cpp | note: candidates are: long long unsigned int rational::gcd() const

How do I circumvent this naming collision without altering the function names? Can I tell the rational::gcd() to look for the other gcd without namespaces? Or with some sort of "not in any" namespace?

Here's the relevant code:

rational.hpp

class rational {
    friend unsigned long long gcd(unsigned long long x, unsigned long long y);

public:
    unsigned long long gcd() const;
};

rational.cpp

unsigned long long gcd(unsigned long long x, unsigned long long y) {
    if (x == y) return x;

    //Euclidean method
    unsigned long long diff;
    while (x != 0 && y != 0) {
        if (x > y) {
            diff = x - y;
            x = diff;
        } else {
            diff = y - x;
            y = diff;
        }
    }
    return (x == 0) ? y : x;
}

unsigned long long rational::gcd() const {
    return gcd(nominator, denominator);
}

Thanks in Advance,
Nick

If you want the friend function then preceed the function name by :: return ::gcd(nominator, denominator);

To generalize:
:: stands for scope resolution operator( I know you know this) which has two operand : the scope[1] and the object/function.
When you don't write the scope explicitly ( like ::gcd() ) it means you are referring to the global scope.

[1] Scope can be a Class or namespace.

Thanks guys, worked like a charm and I understand it too. woopiedoo.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.