I just started working with a team that is using reinterpret_cast
when clearly it should be dynamic_cast
. Although they are using reinterpret_cast
the code still seems to work just fine so I decided to leave it alone until recently when it final stopped working.
struct Base {
virtual void do_work() = 0;
};
struct D1 : public Base {
virtual void do_work();
std::vector<int> i;
};
struct D2: public D1 {
void do_work()
};
struct Holds_data {
std::vector<int> i;
};
struct Use_data : public Holds_data {
virtual void do_work();
};
struct A : public Use_data, public Base {
void do_work();
};
//case 1
// this code works
Base* working = new D2();
D2* d2_inst = reinterpret_cast<D2*>(working);
//case 2
Base* fail = new A();
A* A_inst = reinterpret_cast<A*>(fail); // fails
A* A_inst = dynamic_cast<A*>(fail); // works
in case 1 there does not seem to be a problem reinterpret cast SEEMS to work just fine. in case 2 i noticed the internal data of std::vector seems to be corrupted when using reinterpret cast
My question is why does case 1 pass? Shouldn't there be data corruption within the std::vector?