The assignment operator is used to copy the values from one object to another "already existing object".
Eg: classA objectone(5); //Calls classA constructor.
classA objectTwo; //Calls classA default constructor.
objectTwo = objectone; // Calls classA assignment operator.
Eg:
ClassA object1(5) ; //calls classA constructor,
ClassA object2 = object1;//Calls classA's copy constructor.
A "Copy constructor " is a special constructor that initializes a new object from an existing object.
Eg: classA objectone(5); //Calls classA constructor.
classA objectTwo; //Calls classA default constructor.
objectTwo = objectone; // Calls classA assignment operator.
- In this case,objectTwo has already created by the time assignment is executed.consequently the classA assignment operator is called.
Eg:
ClassA object1(5) ; //calls classA constructor,
ClassA object2 = object1;//Calls classA's copy constructor.
A "Copy constructor " is a special constructor that initializes a new object from an existing object.
- The assignment operator copies to existing objects,and the copy constructor copies to newly created objects..
- If a new object has to be created before copying can occur,the copy constructor is used.
- When instantiating one object and initializing it with values from another object.
- When passing an object by value.
- when an object is returned from a function by value.