Stephan Kurpjuweit wrote:
Hi,
could you please help me with the following example?
struct Base
{
virtual Base& operator = (const Base &k) {}
};
struct Derived: public Base
{
// 1
virtual Derived& operator = (const Derived &k) {}
// 2
virtual Base& operator = (const Base &k) {}
};
int main(int argc, char* argv[])
{
Derived *dp = new Derived();
Base *bp = new Derived(*dp);
*bp = *dp;
return 0;
}
Why does the assignment in main lead to a call to the second assignment
operator (// 2) and not to the first one (//1)?
...
Because selection of candidate functions for overload resolution is
based on _static_ type of the object. In this case static type of
left-hand side of the assignment is 'Base'. This means that only
'Base::operator=(const Base&)' is considered (and, therefore, chosen) by
overload resolution.
Now, since 'Base::operator=(const Base&)' is declared as 'virtual', the
choice of actual function to call will be based on _dynamic_ type of the
object. In this case dynamic type of left-hand side of the assignment is
'Derived', which means that 'Derived::operator=(const Base&)' will be
called.
--
Best regards,
Andrey Tarasevich