0

What is the difference between returning *this or the given argument in implementation of operator= in C++? Is using one of them better or more useful? if yes, why?

   class Object {
   public:
      Object operator=(Object Obj) {
         return *this;
      }
   }

vs.

   class Object {
   public:
      Object operator=(Object Obj) {
         return Obj;
      }
   }
Pete Fordham
  • 2,278
  • 16
  • 25
  • 1
    You should be returning a reference to the current object, not a brand new object. – PaulMcKenzie May 10 '20 at 15:52
  • Does this answer your question? [What is The Rule of Three?](https://stackoverflow.com/questions/4172722/what-is-the-rule-of-three) – Spencer May 10 '20 at 15:54

1 Answers1

1

X& operator=( X const& ) { return *this; } matches the semantics of = on an int. The other suggestions you gave do not. When in doubt match the semantics of int.

Yakk - Adam Nevraumont
  • 262,606
  • 27
  • 330
  • 524