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

 

5 comments:

Nicolae said...

simple & very nice explanation.
well done.

Anonymous said...

Cheers man! Exactly what I was looking for.

Term Papers said...

I have been visiting various blogs for my term papers writing research. I have found your blog to be quite useful. Keep updating your blog with valuable information... Regards

Anonymous said...

Cool explanation.

Anonymous said...

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