Click to See Complete Forum and Search --> : dynamic_cast


dav79
October 13th, 2002, 07:17 AM
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.

Graham
October 13th, 2002, 09:50 AM
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.

kuphryn
October 13th, 2002, 11:25 AM
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

jfaust
October 13th, 2002, 11:37 AM
This works:


A *a = new B();
B *b = dynamic_cast<B*>(a);


Jeff

dav79
October 14th, 2002, 03:26 AM
Thank you very much.
In fact, really, I didn't switch RTTI option on.