By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
432,009 Members | 1,487 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 432,009 IT Pros & Developers. It's quick & easy.

casting primitive type to user-defined type works in usage

P: n/a
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 '06 #1
Share this Question
Share on Google+
2 Replies


P: n/a
xl***************@gmail.com 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".
Apr 15 '06 #2

P: n/a

red floyd wrote:
xl***************@gmail.com 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 '06 #3

This discussion thread is closed

Replies have been disabled for this discussion.