Amin Khormaei
Amin Khormaei

Reputation: 369

how can i define an operator overloading function to compare two objects from two different classes?

I know how to define operator overloading function for two objects from the same class, but I search everywhere on the net or other topics in StackOverflow and I didn't get the correct answer.

I need a simple example to add or compare to objects from different classes. I don't know if I want to define the operator overloading outside the classes, should I make that the friends of two classes or something else.

Upvotes: 0

Views: 53

Answers (1)

cdhowie
cdhowie

Reputation: 169028

This is a good case for using free operators.

bool operator==(TypeA const & a, TypeB const & b) {
  // Do comparison
}

bool operator!=(TypeA const & a, TypeB const & b) {
  return !(a == b);
}

bool operator==(TypeB const & b, TypeA const & a) {
  return a == b;
}

bool operator!=(TypeB const & b, TypeA const & a) {
  return a != b;
}

You should only make them friends of the revelant types if it is necessary; if the state can be fully observed from public members, there is no need to make them friends.


There is an alternative approach, however: if values of these types can be considered equal, that implies that one could be converted to the other. If that is the case, they could be compared after conversion:

TypeA a{createTypeA()};
TypeB b{createTypeB()};

bool result = a == TypeA{b};

Upvotes: 3

Related Questions