c++ - Strange behavior of null pointer -
this question has answer here:
i created null
pointer of class app, somehow method of null
object(of app) working. here code:
#include "app.h" #include <iostream> using namespace std; int main() { app* pointer = null; pointer->print(); system("pause"); }
attached header file
#pragma once #include <iostream> using namespace std; class app { private: int x; int y; public: app(void); ~app(void); app(int a, int b) { x=a; y=b; } void print() { cout<<"hello world"<<endl; } };
the running result screen in : hello world
. why that?
undefined behaviour - undefined. can happen, including appearance of behaving correctly.
for case, specifically, might want check out generated assembly program. you'll find compiler has optimized code , inlined printout or called directly rather invoking through pointer/table lookup.