What is the difference between overloading the operator = in a class and the copy constructor?
In which context is each one called?
I m
In your case neither is used as you are copying a pointer.
Person p1("Oscar", "Mdderos");
Person extra;
The copy constructor
Person P2(p1); // A copy is made using the copy constructor
Person P3 = p2; // Another form of copy construction.
// P3 is being-initialized and it uses copy construction here
// NOT the assignment operator
An assignment:
extra = P2; // An already existing object (extra)
// is assigned to.
It is worth mentioning that that the assignment operator can be written in terms of the copy constructor using the Copy and Swap idium:
class Person
{
Person(std::string const& f, std::string const& s);
Person(Person const& copy);
// Note: Do not use reference here.
// Thus getting you an implicit copy (using the copy constructor)
// and thus you just need to the swap
Person& operator=(Person copy)
{
copy.swap(*this);
return *this;
}
void swap(Person& other) throws()
{
// Swap members of other and *this;
}
};