Fun With Virtual Assignment

7 09 2011

All C++ classes have an assignment operator. If a class definition does not explicitly declare assignment operator, it will be automatically generated by the compiler. Its presence cannot be avoided, but it can be disabled either by declaring it private (compilation fails if other classes try to access it) or declaring it without giving a definition (link will fail if any piece of code tries to access it). The automatically generated assignment operator takes a const reference to the class type itself as its argument.

Many C++ textbooks claim that assignment operator cannot be inherited, but that is simply not true. While it is true that an inherited operator cannot be easily accessed, it still exists: A phenomenon called name hiding will make the base class version difficult to access because the automatically generated derived class version provides a match in a narrower scope. (I’ll write a separate article about the mechanics of name hiding some time in the future.)

The obvious way for a derived class to allow access to its base class assignment operator is by adding a “using Base::operator=” declaration in its definition. Alas, now the derived class technically has an assignment operator so its normal assignment operator will not be automatically generated. As a result, an object of the derived type can still be assigned to another object of the derived type, but only the base part will ever be actually assigned. A way around this is to manually define the assignment operator which would have been generated, but this can be tedious and error prone, and generally not recommended.

But instead of just allowing access to the base class assignment operator, what if the derived class overrides it instead? As surprising as it sounds, this is possible: an assignment operator can be declared virtual and later be overridden by the derived class. This means that the derived class will start getting “notifications” when new values are assigned to it thru its base class interface. If the assignment operator is non-virtual, then something called object slicing will happen when a derived object is assigned a value thru its base class interface – in other words, the derived class would have no idea that the base class data have changed.

Here is some code for experimenting.

Advertisements

Actions

Information

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s