0

I am trying to understand how to implement a class-object. I want to know what is main difference between the following two class assignment operators.

Point Point::operator=(const Point & p)
{
    if(this == &p)
        return *this; 
    m_x = p.m_x;
    m_y = p.m_y;

    return *this;    
}

And this one

Point & Point::operator=(const Point & p)
    {
        if(this == &p)
            return *this; 
        m_x = p.m_x;
        m_y = p.m_y;

        return *this;    
    }

I can see, the latter one returns a reference to an object but I don't see any practical difference. For example, both of them works fine, when I try to do something like this:

Point point2, point3;
point3 = point2 = point1;
Keith Thompson
  • 254,901
  • 44
  • 429
  • 631
Mo Moallim
  • 33
  • 3
  • possible duplicate of [Why must the copy assignment operator return a reference/const reference?](http://stackoverflow.com/questions/3105798/why-must-the-copy-assignment-operator-return-a-reference-const-reference) – user657267 Oct 15 '14 at 23:46
  • The first one makes an extra copy. – Neil Kirk Oct 16 '14 at 00:22
  • Additionally: both of these assignment operators is invalid, undefined behavior. Comparing a pair of raw pointers to class instances is defined only if both class instances are members of the same array/vector. On nearly all C++ implementations, any pointer comparison of this type will produce the expected results, however this is technically non-portable, invalid C++. – Sam Varshavchik Oct 16 '14 at 00:52

0 Answers0