What would be useful for dynamic_cast siblings?

Now I'm reading Scott Myers' Effective C ++. Edification! Clause 2 mentions that dynamic_cast can be used not only for downcasts, but also for sibling. Can someone provide a (reasonably) laid-back example of its use for brothers and sisters? This stupid test prints 0 as it should, but I cannot imagine any application for such conversions.

#include <iostream> using namespace std; class B { public: virtual ~B() {} }; class D1 : public B {}; class D2 : public B {}; int main() { B* pb = new D1; D2* pd2 = dynamic_cast<D2*>(pb); cout << pd2 << endl; } 
+7
c ++ inheritance dynamic-cast siblings
source share
2 answers

The proposed scenario does not match the sidecast , which is usually used for casting between pointers / links of two classes and pointers / links belong to a class object, which both comes from two classes. Here is an example:

 struct Readable { virtual void read() = 0; }; struct Writable { virtual void write() = 0; }; struct MyClass : Readable, Writable { void read() { std::cout << "read"; } void write() { std::cout << "write"; } }; int main() { MyClass m; Readable* pr = &m; // sidecast to Writable* through Readable*, which points to an object of MyClass in fact Writable* pw = dynamic_cast<Writable*>(pr); if (pw) { pw->write(); // safe to call } } 

Live

+6
source share

It is called cross-cast, and it is used when a class inherits from two different classes (not vice versa, as shown in your question).

For example, given the following class hierarchy:

 AB \ / C 

If you have pointer A for object C , you can get pointer B to this object C :

 A* ap = new C; B* bp = dynamic_cast<B*>(ap); 
+2
source share

All Articles