federico-busato / Modern-CPP-Programming

Modern C++ Programming Course (C++03/11/14/17/20/23/26)
https://federico-busato.github.io/Modern-CPP-Programming/
11.91k stars 798 forks source link

[Polymorphism] Sidecast example wrong #70

Closed Ingerdev closed 7 months ago

Ingerdev commented 7 months ago

Page 485

example:

struct A {
    virtual void f() { cout << "A"; }
};
struct B1 : A {
    void f() override { cout << "B1"; }
};
struct B2 : A {
    void f() override { cout << "B2"; }
};

B1 b1;
B2 b2;
dynamic_cast<B2&>(b1).f(); // print "B2", sidecasting
dynamic_cast<B1&>(b2).f(); // print "B1", sidecasting

Instead of printing anything, It throws "bad_cast" as expected and described at page 489.

federico-busato commented 7 months ago

thanks for reporting it, @Ingerdev