Odd behavior of operator=() in diamond inheritance situation

J

Juha Nieminen

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?

I'm using gcc 4.3.1.
 
J

James Kanze

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::eek:perator=, 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:).
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top