Darlyn
Darlyn

Reputation: 4938

Friends function declaring as member function

Having code

struct node
{
    node(int X , int Y):X(X),Y(Y){};
    int X;
    int Y;
    friend bool operator ==(const node &X, const node &Y);
};


int main()
{
    node one(5,5);
    node two(5,5);
    if ( one == two )
    {
       cout << " true " << endl;
    }
    return 0;
}

If i declare operator == as

bool node::operator ==(const node &X, constnode &Y)
{
    return (X.X == X.Y && Y.X == Y.Y);
}

it requires one argument , however when i declare it as

bool operator ==(const node &X, constnode &Y)
{
    return (X.X == X.Y && Y.X == Y.Y);
}

It requires two. I know defined by language , first definition requires one argument becouse the second is *this.

And the second definition its outside definition of operator == ( global ) which is not bound to any structure thu it does not pass *this in it.

But it is still defined as "friend" this basicly states ( by first definition ) that member function is friend function of its own class. How is this possible? Why does this compile?

Upvotes: 2

Views: 70

Answers (2)

zett42
zett42

Reputation: 27756

A method declared as friend is practically not a method of the class, but a global function outside of the class, in the same namespace as the class.

So the following inline definition ...

struct node
{
    node(int X , int Y):X(X),Y(Y){};
    int X;
    int Y;
    friend bool operator ==(const node &lhs, const node &rhs) {
        return (lhs.X == rhs.X && lhs.Y == rhs.Y);
    }
};

... is the same as ...

bool operator ==(const node &lhs, const node &rhs)
{
    return (lhs.X == rhs.X && lhs.Y == rhs.Y);
}

This is why your first definition of operator== is not a valid definition for the method declared as friend.

If you define the global operator== outside of the class, you actually only need the friend declaration if the global function requires access to private members of the class. In your case this is not required, because X and Y are public.

Upvotes: 3

Abhishek Kumar
Abhishek Kumar

Reputation: 3

This is because first definition makes the operator== member function of node. Thus it can access this pointer so first pointer is implicitly this and you can carry on with one argument.

Second definition makes operator== friend function of node. Now friend function accesses members of a class by taking their references as it has no access to this pointer. Thus we need to specify the two parameters expolicitly.

Hope it helps

Upvotes: 0

Related Questions