-
dynamic_cast
Hi!
#include <iostream.h>
class A
{
public:
virtual void f(){};
};
class B : public A {};
void main()
{
A *a = new A();
B *b = dynamic_cast<B*>(a);
}
Whats wrong with code above..? Visual C++6.0 compiler compiles it normally, but then has generates Debug Error.
-
The most obvious thing that's wrong is that a is not a B, so the cast should fail. It ought to return 0 as the pointer value. Since it doesn't I suspect that you don't have RTTI switched on in your VC++ project settings.
-
Class B is derived from Class A. However, Class A knows nothing about Class B. Thus you cannot dynamically cast class B from class A. In your design, the cast has is one-directional.
Kuphryn
-
This works:
Code:
A *a = new B();
B *b = dynamic_cast<B*>(a);
Jeff
-
Thank you very much.
In fact, really, I didn't switch RTTI option on.