Object-oriented type erasure

In object-oriented languages, we deal with abstracted types all the time. Any program that operates entirely on the pointers (or references) to the base class, while the concrete derived classes are not known until runtime, can be seen as a kind of type erasure. This approach is particularly popular in Java, but can be implemented in C++ as well (although, remember that just because you can do it, doesn't mean you should).

In order to use the object-oriented approach, our specific types must inherit from a known base class:

class Object {};class Int : public Object {    int i_;    public:    explicit Int(int i) : i_(i) {}};

Immediately, we run into a problem—we want to sort an array of integers, but a built-in type is ...

Get Hands-On Design Patterns with C++ now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.