Re: Why assignment operator is'nt inherited?
vj wrote:
Here is the excert from the book -
"In addition, the operator= doesn't inherit because it performs a
constructor-like activity. That is, just because you know how to
assign all the members of an object on the left-hand side of the =
from an object on the right-hand side doesn't mean that assignment
will still have the same meaning after inheritance."
-- Thinking in C++, Bruce Eckel , Pg 631
That's a pretty wierd statement. Assignment operators don't do
constructor like activities at all. You make mistakes if you
think about them that way as you must take care of the already
constructed things in the left hand side of the operator.
The C++ language doesn't really define inheritance. Inheritance
of member functions is just an effect of the defined behavior of
base class name resolution. The reason operator= doesn't appear
to inherit is because the fact that there's always a copy assignment
operator in the derived class (either declared expclicitly by
the programmer or implicitly by the compiler) that hides any
base class.
If you bring the name forward with a using declaration, the op
inherits as any other function:
struct base {
base& operator=(const base&) {
cout << "base op=";
return *this;
};
};
struct derived : base {
using base::operator=;
derived& operator=(const derived&) {
cout << "derived op=";
return *this;
}
};
int main(int argc, char* argv[])
{
base b;
derived d;
d = b; // prints base op=
return 0;
}
It's similar semantic rules that keep a templated function from
ever being a copy constructor.