"object is NULL" ---- Actually it's a pointer that's NULL. There is no object here.
As to why it works, simple: C++ offers only guarantees about what will work. It promises nothing about what will not work. So just because something appears to be doing what you intend does not mean the program is correct!
In this case, since the method doesn't do anything with the "this" pointer, the fact that that pointer is garbage doesn't matter. You cannot be assured of something like this always working, but that's the most likely explanation for the behavior you're seeing.
Yes I believe the fact that it doesn't use "this" is correct -- more specifically, because it does not use *any* other class members (which would require using "this"). Basically thec->showthis() is equivalent to saying:
showthis(thec);
...where "thec" is a hidden parameter passed as "this" to all non-static class member functions when invoked....so from there it goes to show that showthis() is just fine until you actually attempt to modify non-static data which would require calling up the specific instance of the class in question (i.e. thec/this)...that's where you get the fun screen.
Heh, thanks. But it was more of a test than a question.
I need you to explain why it's working and doing what it does.
And what if I have a compiler where this code doesn't "work"? Do I need to explain that also?
You have constructs in C++ that are considered "undefined behaviour" (UB). The code you have is UB, and there is no need to explain anything. That code could run on that compiler using a certain option, and crap out if another compiler option is used. Someone could develop a compiler that could detect code as you've posted, and just issue a diagnostic that the program cannot continue when you run the code.
C++ isn't like any of the other languages, where bad code automatically produces a diagnostic, i.e. similar to Java or C#. Bad code in C++ (or C) means your program can do anything in particular, including run successfully or crash and burn right away.
Bookmarks