Thursday 11 January, 2007

Assignment operator Vs. Copy constructor

The copy constructor is for creating a new object. It copies a existing object to a newly constructed object.

The assignment operator is to deal with an already existing object.


class MyObject
{
    public:

        MyObject(); // Default constructor
        MyObject(MyObject const & a); // Copy constructor

        // Assignment operator
        MyObject & operator = (MyObject const & a)
};


The copy constructors play an important role, as they are called when class objects are passed by value, returned by value, or thrown as an exception.


// A function declaration with an argument of type MyObject,
// passed by value, and returning a MyObject

MyObject f(MyObject x)
{
    MyObject r;
    ...
    return(r); // Copy constructor is called here
}

// Calling the function :

MyObject a;

f(a); // Copy constructor called for "a"


It should be noted that the C++ syntax is ambiguous for the assignment operator.


MyObject x; x=y;


and


MyObject x=y;


have different meaning.


MyObject a; // default constructor call

MyObject b(a); // copy constructor call

MyObject bb = a; // identical to bb(a) : copy constructor call

MyObject c; // default constructor call

c = a; // assignment operator call

 

6 comments:

Nicu&Natalia said...

simple & very nice explanation.
well done.

Anonymous said...

Cheers man! Exactly what I was looking for.

Anonymous said...

Cool explanation.

Anonymous said...

Exact thing i was looking for ..Very well explained! thanks!

Unknown said...

Don't you think it should be:
MyObject(const MyObject &a); // Copy constructor
// Assignment operator
MyObject & operator = (const MyObject &a)

Anonymous said...

Thanks very short and effective blog. I looked for this info in many places but only found it here.

MyObject b(a); // copy constructor call
MyObject bb = a; // identical to bb(a) : copy constructor call

one of the least documented ambiguous syntax of C++. very hard to find.

regards.