Ayto Maximo
Ayto Maximo

Reputation: 145

The proper way to overload binary operation

I'm new in C++, so, please, go easy on me :) I've found two different ways to overload binary operator in c++.

The first one (from book "Object-Oriented Programming in C++", Robert Lafore):

class Distance
{
private:
    int value;

public:
    Distance() : value(0) {}
    Distance(int v) :value(v) {}

    Distance operator+(Distance) const;
};

Distance Distance::operator+(Distance d2) const
{
    return Distance(value+d2.value);
}

And another one, with using of friend funcs (from the Internet)

class Distance
{
private:
    int value;

public:
    Distance() : value(0) {}
    Distance(int v) :value(v) {}

    friend const Distance operator+(const Distance& left, const Distance& right);
};

const Distance operator+(const Distance& left, const Distance& right)
{
    return Distance(left.value + right.value);
}

All these cases make it possible to write following code like this:

Distance d1(11);
Distance d2(5);
Distance d3 = d1 + d2;

My question: what is the main difference of these cases? Maybe some advantages or disadvantages. Or some kind of "good programming manners"?

Thank you in advance for your wisdom! :)

Upvotes: 1

Views: 68

Answers (2)

Jarod42
Jarod42

Reputation: 217593

There are several subtle differences including:

The non member way allow to have both

42 + Distance(42);
Distance(42) + 42;

Whereas the member way only allows

Distance(42) + 42;

Upvotes: 2

songyuanyao
songyuanyao

Reputation: 172934

Distance could be converted from int implicitly. Then the 2nd style makes it possible to use the opeartor+ with an object of Distance used as the right operand.

Distance d1(11);
Distance d2(5);
Distance d3 = d1 + d2; //fine
Distance d4 = d1 + 5;  //fine
Distance d5 = 5 + d1;  //fine

The 1st style only supports using opeartor+ with an object of Distance used as the left operand. i.e.

Distance d1(11);
Distance d2(5);
Distance d3 = d1 + d2; //fine
Distance d4 = d1 + 5;  //fine
Distance d5 = 5 + d1;  //fail

Upvotes: 2

Related Questions