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;
      }
   }
2
  • 1
    You should be returning a reference to the current object, not a brand new object. Commented May 10, 2020 at 15:52
  • Does this answer your question? What is The Rule of Three? Commented May 10, 2020 at 15:54

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.