Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Complex dynamic_cast in c++

I have the following case in C++:

  • Abstract base classes Abstract1 and Abstract2. They are unrelated.
  • A class Foo deriving from both Abstract1 and Abstract2

I am in a compilation unit where I have no information about class Foo (no declaration, no definition). Only Abstract1 and Abstract2 are known. (Actually, Foo is even defined in a DLL)

Will dynamic_cast allow casting from Abstract1* to Abstract2*? Is this a standard?

like image 340
galinette Avatar asked Nov 20 '14 14:11

galinette


1 Answers

What you describe is a so-called cross-cast. For dynamic_cast<T>(v), the standard specifies in [expr.dynamic.cast]/8

If C is the class type to which T points or refers, the run-time check logically executes as follows:

  • If, in the most derived object pointed (referred) to by v, v points (refers) to a public base class subobject of a C object [..]

  • Otherwise, if v points (refers) to a public base class subobject of the most derived object, and the type of the most derived object has a base class, of type C, that is unambiguous and public, the result points (refers) to the C subobject of the most derived object.

That will work even with no information about Foo's existence in the translation unit that contains the cast.

You should check out this question too.

like image 145
Columbo Avatar answered Oct 21 '22 03:10

Columbo