I have gone through [question] (What's the difference between assignment operator and copy constructor?) and understood difference between a copy constructor and assignment operator. Now my question is although copy constructor initializes the previously uninitialized object where as assignment operator replaces data from previously initialized object what's the difference in terms of final outcome. I am thinking that final outcome in both case comes out to be same right? In the end after copying via (CC) we get the same output and even after using (AO) we get the same output. Am I making sense here? Can someone please clarify what is the difference in terms of real world application?
Other than what you said, there is no difference.
The CC works on new unitizialied objects (it´s a constructor after all), the operator on existing ones.
The use of the CC could be replaced with the normal constructor and then the assignment op (in usual classes), but this would be not as efficient as the direct construction with copied data.
Eg.
class C
{
private:
vector<int> v;
public
C()
{
//fill v with 10^9 slowly generated random numbers, takes ca. 2 days
}
C(const C& c) //could be auto-generated in this case
{
v = c.v;
}
C &operator=(const C& c) //could be auto-generated in this case
{
v = c.v;
return *this;
}
};
...
C oldc;
...
//either
C newc(oldc);
//or
C newc; //takes 2 days
newc = oldc;
Another reason, some nontrivial classes have no (public) default constructor and can only be created by copying existing objects from somewhere.