0

std::bad_cast: https://en.cppreference.com/w/cpp/types/bad_cast

An exception of this type is thrown when a dynamic_cast to a reference type fails the run-time check (e.g. because the types are not related by inheritance)

So, if the types are not related by inheritance then it throws an error, so how it the following quote hold true?

https://stackoverflow.com/a/332086/462608

You can use it for more than just casting downwards – you can cast sideways or even up another chain.

What does this quote mean? Please give examples.

Aquarius_Girl
  • 21,790
  • 65
  • 230
  • 411
  • 1
    Explained [here](https://en.cppreference.com/w/cpp/language/dynamic_cast#Example) -- look for 'sidecast'. – G.M. Aug 28 '20 at 09:17
  • 1
    You should do a bit of research [what is side-cast or cross-cast in Dynamic_cast in C++](https://stackoverflow.com/questions/35959921/what-is-side-cast-or-cross-cast-in-dynamic-cast-in-c) or [behaviour of dynamic_cast up another chain](https://stackoverflow.com/questions/22489333/behaviour-of-dynamic-cast-up-another-chain) – t.niese Aug 28 '20 at 09:18
  • @t.niese thank you for finding the relevant questions. – Aquarius_Girl Aug 28 '20 at 10:44

1 Answers1

3

Sideways cast would be for example like this:

class Base1 { virtual ~Base1() = default; };
class Base2 { virtual ~Base2() = default; };
class Derived: public Base1, public Base2 {};

int main() {
    Base1* p1 = new Derived;
    Base2* p2 = dynamic_cast<Base2*>(p1);
}

Types Base1 and Base2 are unrelated to each other, but you can cast between the pointers because Derived inherits from both.

I'm not sure what did the original answerer mean by "cast [...] up another chain", but I guess they meant a situation where you would have a Base1* pointer and would cast to Base2 parent.

Yksisarvinen
  • 18,008
  • 2
  • 24
  • 52