Thursday, February 23, 2012

Difference between copy constructor and overloading assignment operator in C++

The basic difference between copy constructor and assignement operator is that
  • Copy constructor is used to create the new object and assigning values of other object to the newly created object
  • Assignment operator is used to assign the values from one object to the already existing object. Here already existing is the main one.
class Copy{

public:
    Copy()  //constructor
    {
        //something
    }
    Copy(const Copy &o) // copy constructor
    {
        //something
    }
    void operator=(const Copy &o) //assignment operator overloading
    {
        //something
    }
};

int main()
{
    Copy C1;
    Copy C2=C1; // calling copy constructor
    Copy C3;
    C3=C2;  // calling assingment operator
}

from the above code snippet, it is clear that in line 21 , it is calling copy constructor because while creating the object C2, we are assigning the other object C1 to C2. where as in line 23 it is calling assignment operator because, we are assigning the object C2 to the already existing object C3. In the above sample code, definition of the copy constructor and assignment operator overloading almost same. but while calling or usage it makes the difference. For more details about copy constructor click here.

No comments:

Popular Posts