CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 5 of 5

Thread: dynamic_cast

  1. #1
    Join Date
    Aug 2002
    Location
    Armenia
    Posts
    62

    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.

  2. #2
    Join Date
    Apr 1999
    Location
    Altrincham, England
    Posts
    4,470
    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


  3. #3
    Join Date
    Feb 2002
    Posts
    5,757
    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

  4. #4
    Join Date
    Mar 2002
    Location
    California
    Posts
    1,582
    This works:

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

  5. #5
    Join Date
    Aug 2002
    Location
    Armenia
    Posts
    62
    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
  •  





Click Here to Expand Forum to Full Width

Featured