#include <iostream>
using namespace std;
class X{
public:
virtual void f(){}
};
class Y {
public:
virtual void g() {}
};
int main()
{
X * x = new X();
Y* y = dynamic_cast<Y*>(x); //A
// Y* y = static_cast<Y*>(x); //B
cout << y << endl;
}
A
compiles whereas B
doesn't. I understand why B
doesn't get compiled but why does A
get compiled although X
and Y
are completely unrelated types?
This is why dynamic_cast
is allowed between unrelated types:
class X{
public:
virtual void f(){}
};
class Y {
public:
virtual void g() {}
};
class Z : public X, public Y {};
int main()
{
X* x = new Z();
Y* y = dynamic_cast<Y*>(x); // compiles and yields non-null pointer
}
The dynamic cast uses the runtime type information. So this is legal do this case but it will return a null pointer. The static cast is evaluated by the compiler.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With