More C++ Idioms/Capability Query

= Capability Query =

Intent
To check at runtime whether or not an object supports an interface.

Motivation
Separating interface from implementation is a good object oriented software design practice. In C++, the Interface Class idiom is used to separate interface from implementation and invoke the public methods of any abstraction using runtime polymorphism. Extending the example in the interface class idiom, a concrete class may implement multiple interfaces as shown below.

Now, if we are given a container of pointers to abstract class, we can simply invoke the roll function on every pointer, as described in the interface class idiom.

Sometimes it is not possible to know in advance whether or not an object implements a particular interface. Such a situation commonly arises if an object inherits from multiple interface classes. To discover the presence or absence of the interface at runtime, a capability query is used.

Solution and Sample Code
In C++, a capability query is typically expressed as a  between unrelated types.

This use of  is often called a cross-cast, because it attempts a conversion across a hierarchy, rather than up or down a hierarchy. In our example hierarchy of shapes and rollables,  to   will succeed only for   and not for , as the later one does not inherit from the   interface class.

Excessive use of capability queries is often an indication of bad object-oriented design.

Related Idioms

 * Interface Class
 * Inner Class