casting primitive type to user-defined type works in usage

X

xllx.relient.xllx

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"
 
R

red floyd

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".
 
X

xllx.relient.xllx

red said:
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.
 

Ask a Question

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

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,997
Messages
2,570,239
Members
46,827
Latest member
DMUK_Beginner

Latest Threads

Top