0

I have a class SomeClass and I wish to implement an overloaded == to compare two instances of this class.

The overloaded == does not make use of any of SomeClass's private members. So, it does not have to be a friend.

How do I make it a non-member, non-friend function?

Currently, this is what my code looks like:

someclass.h

#ifndef SOMECLASS_H
#define SOMECLASS_H

class SomeClass
{
public:
    // Other class declarations, constructors
    friend bool operator==(const SomeClass a, const SomeClass b);
};

someclass.cpp

#include "someclass.h"

// Other stuff 

bool operator==(const SomeClass a, const SomeClass b) {
// do some comparison and return true/false
}
JeJo
  • 30,635
  • 6
  • 49
  • 88
Train Heartnet
  • 785
  • 1
  • 12
  • 24
  • 2
    Put `bool operator==(const SomeClass a, const SomeClass b);` in the header, outside of the class (but inside the same namespace as the class, if any). That's all. – HolyBlackCat Aug 21 '20 at 05:33
  • 1
    By the way, it's call [free function](https://stackoverflow.com/a/4863328/4123703). – Louis Go Aug 21 '20 at 05:45

1 Answers1

5

Like @HolyBlackCat pointed out, you can provide the operator== overload as a free function. It will be a free-function, meaning you can either write

#ifndef SOMECLASS_H
#define SOMECLASS_H

// namespaces if any

class SomeClass
{
    // Other class declarations, constructors
};

bool operator==(const SomeClass& a, const SomeClass& b) noexcept
{
    // definition
}

// end of namespaces if any!

#endif  // end of SOMECLASS_H

or

declare operator== in the header and provide the definition of the free function in the corresponding cpp file

JeJo
  • 30,635
  • 6
  • 49
  • 88
  • 5
    If you declare and define that operator in the header you better declare it inline. Otherwise the linker will complain if you happen to include that header in more than one compilation unit. – bitmask Aug 21 '20 at 06:26