Thread: dynamic_cast vs static_cast

  1. #1
    Registered User
    Join Date
    Jan 2002
    Posts
    11

    Question dynamic_cast vs static_cast

    What is really the difference between dynamic and static cast?

    Code ex:

    float number=43.54;
    cout << static_cast<int>(number) << endl;
    cout << dynamic_cast<int>(number) << endl;

    The compiler (Borland Builder 5) flags an error when I use the dynamic cast (cannot cast from 'float' to 'int'), but if I use static cast - everything works perfectly.

    Why this?

    Thanks
    Xagiber
    I use BorlandBuilder 5

  2. #2
    Me want cookie! Monster's Avatar
    Join Date
    Dec 2001
    Posts
    680
    That's because dynamic cast only works on pointers and references.

  3. #3
    Me want cookie! Monster's Avatar
    Join Date
    Dec 2001
    Posts
    680
    B.t.w. There are a lot of sites with information about this topic.
    Try www.google.com and you can find it out yourself.
    Here's an example: dynamic_cast

  4. #4
    Registered User
    Join Date
    Apr 2002
    Posts
    1,571
    The static_cast operator is the most common. That is the one needed for your situation. Dynamic_cast has to deal with classes and inheritance. When a conversion in your program must access Runtime Type Information (RTTI) you should use the dynamic_cast operator. For examples go look on google. List of the cast operators:

    static_cast
    dynamic_cast
    reinterpret_cast
    const_cast

  5. #5
    Unregistered
    Guest

    Arrow

    Dynamic cast perfoms only polyphormpic cast..

    Dynamic cast is used for converting derived class pointer to base class pointer(Note : The base calss should contain atleasr one virtual function).

Popular pages Recent additions subscribe to a feed