Reputation: 17173
In the following code I use static_cast<B*>
on a void*
, which points to an A
object.
A
and B
are not related in any way. I understand the compiler cannot raise an error against this. But what I don't understand is, how come this actually seems to work when run...? I would expect a segfault or an error of some kind.
#include <iostream>
using namespace std;
class A {
public:
void f() const {
cout << "f" << endl;
}
};
class B {
public:
void q() {
cout << "q" << endl;
}
};
int main(int argc, char** argv) {
A a;
void* p = &a;
static_cast<B*>(p)->q(); // Prints "q"!
return 0;
}
What is the mechanism behind this?
Upvotes: 0
Views: 72
Reputation: 141534
The code causes undefined behaviour (because it dereferences a B *
which does not point to a B
object), which means anything can happen. You should not expect any particular subset of consequences.
To find out what your compiler did, you could inspect the assembly. My guess would be that the compiler generated assembly which would be correct if there were a B
object there: call the function B::q()
with implicit argument p
.
Upvotes: 3
Reputation: 238281
how come this actually seems to work when run...?
Because the behaviour of the program is undefined.
I would expect a segfault or an error of some kind.
When behaviour is undefined, there is no guarantee that there would be a segfault or an error of some kind. It would generally be unreasonable to expect such. When behaviour is undefined, there are no guarantees whatsoever.
Upvotes: 0