Venkatesh wrote in news:99**************************@posting.google.c om
in comp.lang.c++:
Hi All,
I tried the following code and it seems to work. I am really confused
as to how this is possible. Can someone please throw some light?
#include<iostream>
using namespace std;
class Y
{
public :
void foo()
{
cout << "Hello World"<< endl;
}
};
main ()
{
Y *ptr = NULL;
ptr->foo();
}
That the code "works", is one possible result of Undefined Behaviour.
Once you write ptr->something, when ptr is null, you are derefrencing
a NULL pointer, the C++ Standard no longer say's what behaviour your
code exhibits.
It "works", it "doesn't work", your computer grows legs and runs of
with the milkman, all are acceptable.
If your next question is "well why does it work on my implementation",
then probably (just guessing) ptr isn't need to actually call Y::foo(),
since it isn't virtual. So all that happens is ptr is passed to y::foo()
as the 'this' pointer and since Y::foo() doesn't reference 'this' in any
way you Get Away With It(tm).
FYI: main() returns int and only int, also all function's in C++
*must* have a return type, the K&R implicit int has *never* been C++.
HTH.
Rob.
--
http://www.victim-prime.dsl.pipex.com/