C++ FAQ Celebrating Twenty-One Years of the C++ FAQ!!!
(Click here for a personal note from Marshall Cline.)
Section 31:
[31.2] What is "virtual data," and how-can / why-would I use it in C++?

virtual data allows a derived class to change the exact class of a base class's member object. virtual data isn't strictly "supported" by C++, however it can be simulated in C++. It ain't pretty, but it works.

To simulate virtual data in C++, the base class must have a pointer to the member object, and the derived class must provide a new object to be pointed to by the base class's pointer. The base class would also have one or more normal constructors that provide their own referent (again via new), and the base class's destructor would delete the referent.

For example, class Stack might have an Array member object (using a pointer), and derived class StretchableStack might override the base class member data from Array to StretchableArray. For this to work, StretchableArray would have to inherit from Array, so Stack would have an Array*. Stack's normal constructors would initialize this Array* with a new Array, but Stack would also have a (possibly protected) constructor that would accept an Array* from a derived class. StretchableStack's constructor would provide a new StretchableArray to this special constructor.

Pros:

  • Easier implementation of StretchableStack (most of the code is inherited)
  • Users can pass a StretchableStack as a kind-of Stack

Cons:

  • Adds an extra layer of indirection to access the Array
  • Adds some extra freestore allocation overhead (both new and delete)
  • Adds some extra dynamic binding overhead (reason given in next FAQ)

In other words, we succeeded at making our job easier as the implementer of StretchableStack, but all our users pay for it. Unfortunately the extra overhead was imposed on both users of StretchableStack and on users of Stack.

Please read the rest of this section. (You will not get a balanced perspective without the others.)