What would be a use case for dynamic_cast of siblings?
Asked Answered
M

2

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;
}
Menswear answered 3/11, 2016 at 16:21 Comment(1)
Search cross-cast. It is used when a class inherits from two different classes, not the other way around (as in your question).Spirula
L
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

Latrell answered 3/11, 2016 at 16:36 Comment(0)
S
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);
Spirula answered 3/11, 2016 at 16:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.