I stumbled upon some strange behaviour while experimenting with dynamic_cast. This is the code i have
struct Base
{
virtual ~Base(){}
virtual void output() = 0;
};
struct Derived1 : public Base
{
void output() {}
void doDerived_1()
{
std::cout << "derived 1\n";
}
};
struct Derived2: public Base
{
void output() {}
void doDerived_2()
{
std::cout << "derived 2\n";
}
};
int main()
{
Base* base = new Derived1();
Derived2* der2 = dynamic_cast<Derived2*>(base);
// der2 = 0
der2->doDerived_2();
}
Even though der2 is equal to 0 doDerived_2() will still be called and any code inside of it will be executed. The code breaks when i call output() function instead.
Can someone explain to me why this works and doesn't break when it clearly should? Thanks