Automatic operator= creation
Because assigning an object to another
object of the same type is an activity most people expect to be possible,
the compiler will automatically create a type::operator=(type) if you
don’t make one. The behavior of this operator mimics that of the
automatically created copy-constructor; if the class contains objects (or is
inherited from another class), the operator= for those objects is called
recursively. This is called memberwise
assignment. For
example,
//: C12:AutomaticOperatorEquals.cpp
#include <iostream>
using namespace std;
class Cargo {
public:
Cargo& operator=(const Cargo&) {
cout << "inside Cargo::operator=()" << endl;
return *this;
}
};
class Truck {
Cargo b;
};
int main() {
Truck a, b;
a = b; // Prints: "inside Cargo::operator=()"
} ///:~
The automatically generated
operator= for Truck calls
Cargo::operator=.
In general, you don’t want to let
the compiler do this for you. With classes of any sophistication (especially if
they contain pointers!) you want to explicitly create an operator=. If
you really don’t want people to perform assignment, declare
operator= as a
private
function. (You don’t need to define it unless you’re using it inside
the
class.)