Re: virtual assignment operator/polymorphism question
sven.bauer@gmail.com wrote:
Hi,
I have a question following up the following slightly older posting:
http://groups.google.de/group/comp.lang.c++/browse_thread/thread/40e52371e89806ae/52a3a6551f84d38b
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
Base *bp = *dp1;
*bp = *dp2; // Derived::operator= is called
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???
*dp1 = *dp2; calls the compiler supplied operator = i.e.
Derived & operator = (const Derived & k)
The compiler supplied Derived::operator = calls Base::operator=
statically, not dynamically. Hence, it appears you're calling
Base& operator = (const Base &k), but you're not really.
Next time, please post code that compiles.
#include <iostream>
class Base
{
public:
virtual Base& operator = (const Base &k)
{
std::cout << "Base\n"; return *this;
}
};
class Derived: public Base
{
public:
virtual Derived& operator = (const Base &k)
{
std::cout << "Derived\n"; return *this;
}
Derived& operator = (const Derived &k)
{
( * static_cast<Base *>( this ) ) = k;
return *this;
}
};
int main(int argc, char* argv[])
{
Derived *dp1 = new Derived();
Derived *dp2 = new Derived();
*dp1 = *dp2; // Base::operator= is called
// Derived & operator = (const Derived &k);
Base *bp = dp1;
*bp = *dp2; // Derived::operator= is called
return 0;
}