Contents Up << >>

What is "virtual data," and how can I/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 referrent (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. StretchableArray's constructor would provide a "new StretchableArray" to this special constructor.

Pros:

Cons:

In other words, we succeeded at making OUR job easier as the implementor 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.

See the FAQ after the next to find out how much the users "pay." Also: please read the few FAQs that follow the next one too (you will not get a balanced perspective without the others).