c++ - calling non-static member function without instantiation using `reinterpret_cast` -
as it's shown in following code, can call non-static member function a::f
without instantiating object of class. possible when function not bound other member. example, cannot call a::g
in similar fashion.
it seems me call a::f
shown in code below behaves calling static member function. such conclusion correct? how can behavior justified?
#include <iostream> using namespace std; struct { void f() { cout << "hello world!"; } void g() { cout << i; } int = 10; }; int main() { auto fptr = reinterpret_cast<void(*)()>(&a::f); (*fptr)(); // ok // auto gptr = reinterpret_cast<void(*)()>(&a::g); // (*gptr)(); // error! return 0; }
is such conclusion correct? how can behavior justified?
it's undefined behavior.
pretty useless ask how should specifically behave. pick 1 or more list:
- 2)schroedingers cat found dead when open chest1
- your fridge explodes
- you see behavior get
- little demons flying out nostrils
- 1)you time warped point, when put living cat chest2
- ...
- all of above happens simultaneously
void f() { cout << "hello world!"; }
well, fact code doesn't rely on member variable data makes likely, decent implementation works without "crashing".
though, it's ub call class member function without valid class instance, mentioned above.
can't predict happens, or should rely on observations.