Re: virtual assignment operator/polymorphism question
On Apr 12, 1:15 pm, sven.ba...@gmail.com wrote:
I have a question following up the following slightly older
posting:http://groups.google.de/group/comp.lang.c++/browse_thread/thread/=
40e5...
class Base
{
virtual Base& operator = (const Base &k) {}
};
class Derived: public Base
{
virtual Base& operator = (const Base &k) {}
};
int main(int argc, char* argv[])
{
Derived *dp1 = new Derived();
Derived *dp2 = new Derived();
*dp1 = *dp2; // Base::operator= is called
How do you know? I think rather that the compiler generated
derived operator is being called (statically, since it isn't
virtual). This operator, of course, calls the base operator=.
Base *bp = *dp1;
*bp = *dp2; // Derived::operator= is called
Yes, but not the default Derived::operator=.
return 0;
}
While it seems clear to me why *bp = *dp2 leads to the
Derived::operator= being called I do not understand why *dp1 = *dp2
calls the Base::operator=.
What's going on here???
Your Derived::operator= is not a copy assignment operator (since
it doesn't assign a Derived to Derived, but a Base to Derived),
so it doesn't inhibit the compiler from generating its version.
More generally, polymorphism and assignment don't work well
together. If you plan on using a class as a base, it's
generally best to declare the operator= private, and not
implement it (or to derive it from something like
boost::noncopyable).
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34