Monthly Archives: May 2012

In C++ when you create a new class, you have to write an assignment operator. There are three things that every object is expected to do.

1. An object should be able to initialize itself to a default state.  i.e default constructor (e.g TFoo::TFoo() ).

2. An object should be able to initialize itself from another instance of the same class. i.e Copy constructor (TFoo::TFoo(const TFoo&))

3.  An object should be able to assume the semantic state of another instance of the same class. i.e Assignment operator (TFoo::operator = (const TFoo&))

These three function are special in C++. If you do not provide them yourself, C++ provides them for you. And Automatically makes them public. This means you have to define these operations even if you don’t want a client to be able to copy or default construct a particular class. If you don’t want a class to be copied, you have to define an empty constructor and assignment operator yourself and make them private or protected.

Furthermore, the compiler will not guaranteed to create versions of these classes that do exactly what you want them to do. For example, in the case of copying and assignment, the automatic code will do a shallow member wise copy. If you class has pointer members, this is practically never what you want, and even when you don’t have pointer members, this isn’t always the right behavior.

Reference: The Anatomy of the Assignment Operator by Richard Gillam