Because often, compiler generated one is not sufficient.
what was the problem before that raise to the solution like "copy constructors".
To create a copy of the object?
with some examples
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
struct foo
{
foo(int i)
{
arr = newint[i];
}
int* arr;
};
int main()
{
foo x(10); //Create foo object containing array of 10 ints
x.arr[5] = 42; //Modify said array
foo y = x; //Creating a copy of x. Using compiler generated CC which does only shallow copy
y.arr[5] = 9000; //Modifying y array
std::cout << x.arr[5]; //Woops. Totally unexpected. Why does it outputs 9000?
}
We need to have both copy constructor and assigment operator.
When object is initialized, only constructor can be called: foo y = x; //calls copy constructor, not assigment operator
This is because only constructors can initialize object.
Assigment operators work on already initialized objects.