casting primitive type to user-defined type works in usage

Discussion in 'C++' started by xllx.relient.xllx@gmail.com, Apr 15, 2006.

  1. Guest

    Can anyone kindly explain why the following works, even though it's
    undoubtedly a very bad thing to do:

    class Bird
    {
    int age;

    public:
    Bird(int = 21);
    void IFly(void);
    };

    Bird::Bird(int lage)
    {
    age = lage;
    }

    void Bird::IFly()
    {
    age = 21;
    std::cout<<"Bird::IFly"<<std::endl;
    std::cout<<"age: "<<age<<std::endl;
    }

    int main(int argc, char **argv)
    {
    int i;
    Bird *x = reinterpret_cast<Bird*>(&i);
    x->IFly();

    return 0;
    }

    PRINTS: "Bird::IFly"
    "age: 21"
    , Apr 15, 2006
    #1
    1. Advertising

  2. red floyd Guest

    wrote:
    > Can anyone kindly explain why the following works, even though it's
    > undoubtedly a very bad thing to do:
    >
    >[code redacted]


    Because undefined behavior can do anything, including seeming to "work".
    red floyd, Apr 15, 2006
    #2
    1. Advertising

  3. Guest

    red floyd wrote:
    > wrote:
    > > Can anyone kindly explain why the following works, even though it's
    > > undoubtedly a very bad thing to do:
    > >
    > >[code redacted]

    >
    > Because undefined behavior can do anything, including seeming to "work".


    Good enough, Thanks.
    , Apr 15, 2006
    #3
    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. DaKoadMunky
    Replies:
    8
    Views:
    3,310
    Leor Zolman
    May 14, 2004
  2. Replies:
    7
    Views:
    601
    Victor Bazarov
    May 9, 2005
  3. Oodini
    Replies:
    1
    Views:
    1,767
    Keith Thompson
    Sep 27, 2005
  4. Daniel Pitts
    Replies:
    7
    Views:
    474
  5. Gaijinco
    Replies:
    5
    Views:
    312
    James Kanze
    Mar 9, 2009
Loading...

Share This Page