TITLE: compiler-generated assignment operators (Newsgroups: comp.lang.c++.moderated, 7 Nov 96) PROBLEM: According to C++ Primer by Stanley B. Lippman (which is the only book I have to hand) the assignment operator is not inherited from a base class by a derived class. Now, I have a class that is derived from two base classes and each of the base classes has an assignment operator but the derived class doesn't. However, when one derived object is assigned to another, both base class assignments are called. Does this mean that the default memberwise assignment operator that you get given for "free" always calls the assignment operator for all of its base types ? If this is true, and after thumbing through the same book I think that it is, then is this a really obvious thing that I have missed somewhere along the line or should it be spelt out more clearly ? CLAMAGE: clamage@taumet.Eng.Sun.COM (Steve Clamage) You are correct. But why do you think you missed something? Assignment operators are not inherited. Suppose you have this code: class base { ... operator=(const base&); ... }; class derived : public base { ... }; // no operator= declared derived x, y; ... x = y; Inheriting a function means that if the derived class does not override it, the base class function gets used when invoked from the derived class. Our example, if op= were inherited, would then yield static_cast(x).base::operator=( static_cast(y) ); That is, only the 'base' parts of y would be assigned to x, and the 'derived' parts of y would not. But that isn't what happens. Instead, the compiler generates a default version of derived::operator=(const derived&) for you. It performs memberwise assignment in the same order as a constructor would. Since the base class has a user-defined assignment operator, that function is used to assign the base part. If "base" lacked a user-defined assignment operator, the compiler would generate one and call that instead. (Remember, every class has an assignment operator, whether you declare one or not.) In short, whether or not the base class has a user-defined assignment operator, a derived class assignment operator is generated by the compiler if you don't provide one for the derived class. That generated function always invokes some base-class assignment operator. Note: if you write your own assignment operator for a class, you must write every sub-assignment explicitly. Unlike a user-written constructor, the compiler doesn't add any code to handle base classes or members. --- Steve Clamage, stephen.clamage@eng.sun.com [ Send an empty e-mail to c++-help@netlab.cs.rpi.edu for info ] [ about comp.lang.c++.moderated. First time posters: do this! ]