beerbal wrote:
Hello,
I am a bit confused as to how the following snippet would work?
#include <iostream>
class Foo
{
public:
void doSomething()
{
std::cout << "Foo::doSomething()\n";
}
};
int main()
{
Foo* ptr;
ptr->doSomething();
return 0;
}
I compiled this with both g++ and VC and in both cases, program printed
Foo::doSomething() when run.
My question is, since ptr is declared as just a pointer to class Foo,
how/why does the call to doSomething() go thru' even when there is no
object created explicitly?
Dereferencing an uninitialised pointer is undefined behaviour. That
means it might do what you expect, it might do nothing, or it might
delete all the files on your hard drive.
It's pointless to speculate further, but here goes:
Foo::doSomething could be rewritten in C, as such:
doSomething(Foo& f);
Where Foo is just a struct.
Since Foo contains no data, and doSomething() doesn't rely on any data
of Foo, the argument is "optimised" away by the compiler and run as if
it were a standalone function.
Therefore there is no crash.
The behaviour is undefined, and it may or may not, be different
tomorrow... you should not rely on it.
Ben Pope
--
I'm not just a number. To many, I'm known as a string...