Item 31. Covariant Return Types

Generally, an overriding function must have the same return type as the function it overrides:

image

However, this rule is relaxed for what are known as “covariant return types.” If B is a class type, and a base class virtual function returns B *, then an overriding derived class function may return D *, where D is publicly derived from B. (That is, D is-a B.) If a base class virtual function returns B &, then an overriding derived class function may return D &. Consider the following clone operation on a shape hierarchy (see Virtual Constructors and Prototype [29, 99]):

The overriding derived class function is declared ...

Get C++ Common Knowledge: Essential Intermediate Programming 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.