CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3
  1. #1
    Join Date
    Feb 2001
    Posts
    77

    dynamic cast basics

    class Pet{
    public:
    virtual void eat(){cout<<"Pet eating"<<endl;}
    };
    class Dogublic Pet{
    public:
    void eat(){cout<<"Dog eating"<<endl;}
    virtual void sleep(){cout<<"Dog sleeping"<<endl;}
    };

    int main()
    {
    Pet* qq=new Pet;
    //Dog* DD=(Dog*)qq;[1]
    Dog* DD=dynamic_cast<Dog*>(qq);[2]
    DD->eat();[3]
    }
    In the above the compilations for both static cast and dynamic cast go through.But while static cast executes [3] successfully,dynamic casting causes segmentation fault at [3].How do we explain this?


  2. #2
    Join Date
    Oct 2000
    Location
    London, England
    Posts
    4,773

    Re: dynamic cast basics

    the dynamic casting will return NULL because qq is not a dog. Thus then next statement you are doing on a NULL pointer.

    the static casting is dangerous here but you got away with it.


    The best things come to those who rate

  3. #3
    Join Date
    Apr 1999
    Location
    Altrincham, England
    Posts
    4,470

    Re: dynamic cast basics

    Here you see the reason why dynamic_cast exists. The static cast may well have worked by sheer fluke, but it could have just as easily caused mayhem (and in a larger program probably would have). dynamic_cast, however, returns 0 (NULL) because qq is NOT a Dog (and it's dangerous to pretend that it is) - in other words, it's telling you that you did something illegal. static_cast isn't that kind.

    He who breaks a thing to find out what it is, has left the path of wisdom - Gandalf
    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


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