TITLE: Assignment operator considerations PROBLEM: h.b.furuseth@usit.uio.no (Hallvard B Furuseth) BTW, how should operator= be written in classes with multiple inheritance and virtual base classes? RESPONSE: kanze@us-es.sel.de (James Kanze) I've found the following useful: MyType const& MyType::operator=( MyType const& other ) { if ( this != &other ) { this->~MyType() ; new ( this ) MyType( other ) ; } return *this ; } This supposes that you've got the copy constructor right. On the other hand, the compiler handles the problem of calling the constructor for the virtual base class once (and only once), so you have one less problem to think about. RESPONSE: tgakem@ta0.chem.tue.nl (Eric Meijer) if there is a lot of dynamic memory allocation going in in your constructors, this could be very inefficient. For some classes you will only need to copy data in operator=. Then it is a waste to delete memory and immediately allocate it again. My approach would be to call operator= of the base classes like class MyType: public base1, base2: { [blah blah] } MyType const& MyType::operator=(MyType const& other) { base1::operator=(other); base2::operator=(other); /* local stuff */ return *this; } RESPONSE: clamage@taumet.Eng.Sun.COM (Steve Clamage), 8 Jun 94 But this doesn't work if base1 and base2 have common virtual base classes. In that case, they get copied multiple times. (base2::op= doesn't know that base::1op= has already copied the virtual base.) This is wasteful, if not an outright error. Several textbooks on advanced C++ programming explain how to get this right -- as others have noted, you have to be very careful. The basic idea is to have a protected "copy" function in each class which invokes its direct non-virtual base-class copy function(s), then copies its own stuff. The op= for a class invokes the op= for all of its virtual bases, then its own copy function. Ugly and error-prone, since you have to look at all these functions whenever the hierarchy changes. (This still isn't exactly right. Read up on it. Tom Cargill's "C++ Programming Style" is one reference.)