Wrong usage of static_cast: is output undefined or predicted?

Discussion in 'C++' started by Alex Vinokur, Sep 27, 2004.

  1. Alex Vinokur

    Alex Vinokur Guest

    Here is some program in which static_cast is (wrongly) used instead of dynamic_cast.

    Is output of the program undefined or predicted?

    =========== C++ code : foo.cpp : BEGIN ===========
    #include <iostream>
    using namespace std;

    struct B
    {
    virtual void foo1 () { cout << "B::foo1" << endl; }
    virtual void foo2 () { cout << "B::foo2" << endl; }
    };
    struct D1 : public B
    {
    void foo1 () { cout << "D1::foo1" << endl; }
    };
    struct D2 : public B
    {
    void foo2 () { cout << "D2::foo2" << endl; }
    };

    int main ()
    {
    B* pB = new D1;
    // --------------------------
    // Of course, here we should use dynamic_cast
    D2* pD2 = static_cast<D2*> (pB);
    // --------------------------

    pD2->foo1();
    pD2->foo2();

    return 0;
    }

    =========== C++ code : foo.cpp : END =============



    =========== Compilation & Run : BEGIN =============

    $ g++ --version
    g++ (GCC) 3.3.3 (cygwin special)
    [---omitted---]

    $ g++ -W -Wall foo.cpp
    // No errors, no warnings

    $ a
    D1::foo1
    B::foo2


    =========== Compilation & Run : END ===============
     
    Alex Vinokur, Sep 27, 2004
    #1
    1. Advertising

  2. * Alex Vinokur:
    >
    > Here is some program in which static_cast is (wrongly) used instead of dynamic_cast.
    >
    > Is output of the program undefined or predicted?


    UB.

    The code will probably work on most compilers since the derived classes
    do not add anything to or otherwise change the object memory layout.


    > // --------------------------
    > // Of course, here we should use dynamic_cast


    Just say no to casting.

    --
    A: Because it messes up the order in which people normally read text.
    Q: Why is it such a bad thing?
    A: Top-posting.
    Q: What is the most annoying thing on usenet and in e-mail?
     
    Alf P. Steinbach, Sep 27, 2004
    #2
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Jerry Coffin

    static_cast usage

    Jerry Coffin, Oct 7, 2003, in forum: C++
    Replies:
    7
    Views:
    744
    Phlip
    Oct 9, 2003
  2. nin234ATIyahoo.com
    Replies:
    6
    Views:
    1,201
    nin234ATIyahoo.com
    Mar 16, 2005
  3. Bo Peng
    Replies:
    11
    Views:
    1,118
    Victor Bazarov
    Oct 20, 2006
  4. Richard
    Replies:
    9
    Views:
    166
    Richard
    Dec 7, 2006
  5. junyangzou
    Replies:
    13
    Views:
    289
Loading...

Share This Page