0

I give the following example to illustrate my question:

In the first example, operator overloading is insider the class definition:

// Example program 1
#include <iostream>
#include <string>


class Abc
{
  public:
    int a_;
    Abc(int a):a_(a) {};
    bool operator <(const Abc &obj)
    {
      return this->a_<obj.a_;   
    }
};
int main()
{
  Abc myAbc(3);
  Abc yourAbc(4);
  bool b = (myAbc<yourAbc);
  if(b)
     std::cout<<"True";
  else
     std::cout<<"False";


  return 0;
}

In the second example, operator overloading is outsider the class definition:

// Example program 2
#include <iostream>
#include <string>


class Abc
{
  public:
    int a_;
    Abc(int a):a_(a) {};

};

    bool operator <(const Abc &objLeft,const Abc &objRight)
    {
      return objLeft.a_<objRight.a_;   
    }

int main()
{
  Abc myAbc(3);
  Abc yourAbc(4);
  bool b = (myAbc<yourAbc);
  if(b)
     std::cout<<"True";
  else
     std::cout<<"False";


  return 0;
}

In both examples, the codes work well. So my question is which one is better? Or they are the same, and it is only a matter of style. Thanks.

feelfree
  • 11,175
  • 20
  • 96
  • 167
  • 1
    The second one is a bit better. However, it forces you to expose the data member as `public`, so in that sense it is not perfect. Adding *getter* to the class would solve this issue. – Nawaz Feb 02 '16 at 08:49
  • Should switch from `public` to `protected / friend` – Matt Feb 02 '16 at 08:50
  • 1
    @Nawaz or declaring the operator a friend. – eerorika Feb 02 '16 at 08:50
  • 1
    `Or they are the same, and it is only a matter of style` Should be a good idea to have binary operators outside of class, while unary - inside. But it's more a style issue. – Matt Feb 02 '16 at 08:53
  • 1
    Have a look at this answer and its comment section specifically in this matter: http://stackoverflow.com/a/4421729/1025391 – moooeeeep Feb 02 '16 at 08:54

0 Answers0