0

I'm trying to figure out if it is possible to overload the comparison operator for a member of an object. I know it is possible to overload the comparison of two objects, but what about the members specifically?

class Foo()
{
private:
    int a;
    int b;
    int c;
    char set
public: 
    void SetA();
    int GetA();
    void SetB();
    int GetB();
}

Then lets say I wanted to compare a specifically instead of the object as a whole:

int main()
{
    Foo Ab;
    Foo Bc;
    Ab.SetA(1);
    Bc.SetA(4);
    int c {0};
    if(Ab.GetA()>Bc.GetA())
    {
        c=5;
    }
}

Instead of declaring an operator for the objects, is it possible to declare it for Get methods?

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
  • Are you saying you want to compare two `int`s? You can do that. Are you having some trouble trying to compile this? – JohnFilleau Mar 20 '20 at 04:12
  • @John Well i was trying to overload the > comparison. Im trying to experiment with some stuff but i wasn't sure if it possible to overload it with two Get methods. – Jaey Carlson Mar 20 '20 at 04:19
  • You can't define overloaded operators for primitive types. At least one of the operands has to be a user defined type. – JohnFilleau Mar 20 '20 at 04:21
  • How would you want to compare two `int`s using `>` that doesn't follow the built-in notion of greater-than, though? – JohnFilleau Mar 20 '20 at 04:29
  • So then it only possible to overload Ab>Ba. There is no way to overload the comparison between GetA() > GetA(); – Jaey Carlson Mar 20 '20 at 04:29
  • Well if `GetA()` returns an `int`, then no you can't overload it. If `GetA()` returns some user-defined type, then yeah - you can overload it. If you really want I guess you could define a struct `MyInt { int val; }` and define an `operator>(const MyInt&, const MyInt&)` that compares the underlying data in the way you want. – JohnFilleau Mar 20 '20 at 04:31
  • I think this is probably better represented though as a member function of `Foo` called something like `bool compareA(const Foo& other)` that compares the values of `Foo` the way you want. – JohnFilleau Mar 20 '20 at 04:33
  • Yeah ill try defining a structure and use the operator there to compare the data. – Jaey Carlson Mar 20 '20 at 04:39
  • Does this answer your question? [What are the basic rules and idioms for operator overloading?](https://stackoverflow.com/questions/4421706/what-are-the-basic-rules-and-idioms-for-operator-overloading) – L. F. Mar 20 '20 at 09:44

0 Answers0