I have the following code:
using namespace std;
class BaseOk
{
public:
virtual void ImplementMe()
{
};
};
class DerivedOk : public BaseOk
{
public:
void ImplementMe()
{
}
};
class CBase { };
class CDerived: public CBase { };
int main()
{
CBase b; CBase* pb;
CDerived d; CDerived* pd;
pb = dynamic_cast<CBase*>(&d); // ok: derived-to-base
pd = dynamic_cast<CDerived*>(&b); // wrong: base-to-derived -> this doesn't compile
// Polymorphic case
BaseOk b2; BaseOk* pb2;
DerivedOk d2; DerivedOk* pd2;
pb2 = dynamic_cast<BaseOk*>(&d2); // ok: derived-to-base
pd2 = dynamic_cast<DerivedOk*>(&b2); // wrong: base-to-derived -> this returns a NULL pointer
}
The line with the pointer "pd" performs a downcast and I agree that it should fail because the result is a totally different object. My question is: why doesn't the dynamic_cast in that line compile at all instead of just returning a NULL pointer?
I'm using MSVC2012 compiler