Re: Odd behavior of operator=() in diamond inheritance situation
On Mar 2, 1:50 am, "Victor Bazarov" <v.Abaza...@comAcast.net> wrote:
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.
That's doubtlessly the correct explination of what is happening,
but it's not guaranteed. According to the standard: "It is
unspecified whether subobjects representing virtual base classes
are assigned more than once by the implicitly-defined copy
assignment operator."
In practice, of course, most of the time, the virtual base will
be abstract, and not contain any data members, so it won't
matter. Most of the time:-).
--
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