|
-
October 13th, 2002, 07:17 AM
#1
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.
-
October 13th, 2002, 09:50 AM
#2
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.
Correct is better than fast. Simple is better than complex. Clear is better than cute. Safe is better than insecure.
-- Sutter and Alexandrescu, C++ Coding Standards
Programs must be written for people to read, and only incidentally for machines to execute.
-- Harold Abelson and Gerald Jay Sussman
The cheapest, fastest and most reliable components of a computer system are those that aren't there.
-- Gordon Bell
-
October 13th, 2002, 11:25 AM
#3
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
-
October 13th, 2002, 11:37 AM
#4
This works:
Code:
A *a = new B();
B *b = dynamic_cast<B*>(a);
Jeff
-
October 14th, 2002, 03:26 AM
#5
Thank you very much.
In fact, really, I didn't switch RTTI option on.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|