Cross-casting

I’ve been a software engineer for nearly 12 years now, and still I often manage to encounter C++ tricks or techniques that are new to me. This, by the way, is more often than not not down to the ever-evolving nature of the language; more that a lack of formal computer science education and no real propensity to read around the subject has left me with *ahem* gaps in my knowledge.

Yesterday’s neat1 new trick was cross-casting, which allows casting across inheritance hierarchies between unrelated classes. This sounds like it should be illegal, but as long as there’s a common sub-class of the two classes between which you’re trying to cast, and the object you’re trying to cast’s actual type is this sub-class, then the cross-cast will work. For example:

class A
{
public:
virtual ~A();
};
class B
{
public:
virtual ~B();
};
class C : public A, public B
{
};

A* ap = new C;
B* bp = dynamic_cast<b*>(ap);

An interesting2 use-case for this is highlighted in the Capsule pattern which, as the summary states, reduces coupling between application layers. For the uninitiated, reducing coupling is an important goal, and anything that can help achieve that is a useful tool. The example presented in the capsule pattern is the communication of error messages from low-level components to high-level components, without exposing to all the intermediate levels unnecessary details of those errors. It looks like a useful trick. I might just even use it.


1 – Warning: may not be neat.
2 – Warning: may not be interesting.

Leave a comment