Thread: dynamic_cast causing run time error

Threaded View

Previous Post Previous Post   Next Post Next Post
  1. #5
    Programming Sex-God Polymorphic OOP's Avatar
    Join Date
    Nov 2002
    Posts
    1,078
    Originally posted by Micko
    Thanks, I didn't know that.
    Interesting when use
    dg=(Dog *) p;
    it works just fine?
    What type of casting is this?
    Is it C-style cast?
    Yeah, that's a C-style cast. It's result is like a mix of static_cast, reinterpret_cast, and const_cast -- by that I mean it will perform proper pointer arithmetic when casting via a hierarchy which makes it like static_cast, it can convert from pointer-to-const to pointer-to-nonconst like const_cast, and can convert between completely unrelated types, like reinterpret_cast. Try to stay away from C-style casts and use C++ casts instead. They're more specific, can make the intention clearer, and will disallow you from accidently doing more in the cast than you'd like (IE accidently casting away const with a static_cast).

    So, using the c-style cast will work, however it won't check if the conversion is valid, whereas a dynamic_cast will. In general, you want to stay away from dynamic_cast anyways (preferably don't do any casting and solve your problem polymorphically if possible). If you're using dynamic_cast then theres pretty much a 99% chance that you have some constrewed logic in your program and theres probably a better solution. Use dynamic_cast sparingly, and try to only use it during development (try not to us it in a completed project, much like const_cast).

    Aside from this, you should also realize that it's perfectly valid to use a static_cast to go both up and down the class hierarchy and it's preferable over a C-style cast.

    dg=static_cast<Dog *>( p );
    Last edited by Polymorphic OOP; 02-28-2004 at 07:12 AM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. How to monitor process creation?
    By markiz in forum Windows Programming
    Replies: 31
    Last Post: 03-17-2008, 02:39 PM
  2. Crazy errors caused by class, never seen before..
    By Shamino in forum C++ Programming
    Replies: 2
    Last Post: 06-10-2007, 11:54 AM
  3. We Got _DEBUG Errors
    By Tonto in forum Windows Programming
    Replies: 5
    Last Post: 12-22-2006, 05:45 PM
  4. Dikumud
    By maxorator in forum C++ Programming
    Replies: 1
    Last Post: 10-01-2005, 06:39 AM
  5. pointer to array of objects of struct
    By undisputed007 in forum C++ Programming
    Replies: 12
    Last Post: 03-02-2004, 04:49 AM