I was wondering if you guys could help me.
Here are my .h:
Class Doctor {
const string name;
public:
Doctor();
Doctor(string nam
You are almost there. Few noteworthy points:
The name should not be const
qualified. A const
cannot be modified, which is exactly what we want in the assignment operator.
The C++ keyword is class
and not Class
as your code has it (it'll give you compile errors)
As Michael Burr notes: "It should be noted though that if the class simply contains other classes that already properly support assignment (as in this case with a simple string member), the implicit, compiler-generated operator=() will work just fine." Here, in your case, the only member string
has a proper op=
. So explicitly defining is redundant.
Meeh's solution is almost there. The only thing it doesn't talk about is self-assignment. Read FAQ 12.
Assignment is one the Big Three member functions FAQ 27.10. Look it up. It says, requirement to implement either one of copy ctor, op= or the dtor usually implies that you'd need to implement the other two as well.
The corrected code sample should be something like this:
class Doctor {
string name;
public:
Doctor& operator=(Doctor const& o) {
if (&o != this) name = o.name;
return *this;
}
// ...
};