Dereferencing nullptr ? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

Dereferencing nullptr ?

Hello fellow community members. How come this works? I came across this code in one of YouTube tutorials. Excepted outcome was crash, but this code executes just fine? https://code.sololearn.com/c44x14kGEnTc/?ref=app

18th Aug 2019, 6:48 PM
Nemanja Kuzmić
Nemanja Kuzmić - avatar
1 Answer
+ 5
This used to be done way back, before standard C++, before static functions where allowed in classes as a workaround. You see, class functions are not stored with the actual object, only variables are ( and the vtable ). So in order to call a class function there is no need to dereference the nullptr and no crash happens. If your class was non static AND accessed one of the object's variables, only then would it need to dereference the object, and then it would crash. Nevertheless this way is non portable and not guaranteed to work everywhere. There is still an ongoing discussion over whether this is undefined behaviour or not: ( created over 19 years ago ) http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#232 Just out of curiosity, what tutorial still teaches this anyway?
18th Aug 2019, 7:21 PM
Dennis
Dennis - avatar