7

I'm reading Scott Meyers' More Effective C++ now. Edifying! Item 2 mentions that dynamic_cast can be used not only for downcasts but also for sibling casts. Could please anyone provide a (reasonably) non-contrived example of its usage for siblings? This silly test prints 0 as it should, but I can't 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;
}
sigil
  • 815
  • 8
  • 16
  • Search `cross-cast`. It is used when a class inherits from two different classes, not the other way around (as in your question). – barak manos Nov 03 '16 at 16:32

2 Answers2

6

The scenario you suggested doesn't match sidecast exactly, which is usually used for the casting between pointers/references of two classes, and the pointers/references are referring to an object of class which both derives from the two classes. Here's an example for it:

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

songyuanyao
  • 169,198
  • 16
  • 310
  • 405
3

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

For example, given the following class-hierarchy:

A   B
 \ /
  C

If you have an A pointer to a C object, then you can get a B pointer to that C object:

A* ap = new C;
B* bp = dynamic_cast<B*>(ap);
barak manos
  • 29,648
  • 10
  • 62
  • 114