0

I was always overriding operators like this:

class MyClass {
public:
    ...
    MyClass operator+(const MyClass&) const;

private:
    int some_number = 5;
}

 

MyClass MyClass::operator+(const MyClass& rhs) const
{
    return MyClass(some_number + rhs.some_number);
}

But today I realized you can create operators with the 'friend' keyword too:

class MyClass {
public:
...
friend MyClass operator+(const MyClass&, const MyClass&);

private:
    int some_number = 5;
} 

 

MyClass operator+(const MyClass& lhs, const Myclass& rhs)
{
    return MyClass(lhs.some_number + rhs.some_number);
}

Which would be the preferred way considering I want left-sided and right-sided operators and I also (try to) follow the Core Guidelines?

Not Szwagi
  • 81
  • 2
  • 10
  • 1
    Fyi, this is worth the read: [Operator Overloading](https://stackoverflow.com/questions/4421706/operator-overloading). Particularly the section on [The Decision between Member and Non-member](http://stackoverflow.com/questions/4421706/operator-overloading/4421729#4421729). – WhozCraig Nov 20 '16 at 10:38
  • Don't confuse **overloading** and **overriding**. Those are very different things! – Christian Hackl Nov 20 '16 at 10:40

1 Answers1

0

The preferred way is to not even make it a friend:

MyClass operator+(MyClass lhs, Myclass const& rhs)
{
    return lhs += rhs;
}

Of course, this does rely on operator+= but that is the more fundamental operation. += alters its left-hand side and should be a member.

MSalters
  • 173,980
  • 10
  • 155
  • 350