Kai-Uwe Bux said:
It may print anything: "a->Display()" dereferences an uninitialized
pointer
variable. The program has undefined behavior.
I do not believe that is true. a->Display() is not actually "dereferencing"
the pointer. The Display() method exists regardless of whether or not any
instances of 'A' are created, and it will get invoked via a->, regardless of
the value of 'a'. That is, the ability to call methods in the class is not
dependent on having a valid, non-NULL pointer. Of course, what happens if
the method attempts to make use of data members (like 'dCol' in the example)
within the class, since the 'this' pointer is uninitialized (or NULL in this
case), is completely unknown.
For example, if Display() were written thus:
const void * Display(void) const { return this; }
Then:
A *a = (A *)0x12345678;
printf("a is %p", a->Display());
....should print: "a is 12345678" without any difficulty, even though the
memory at the address assigned to 'a' is likely to contain garbage, because
it makes no use of the 'this' pointer (which is silently passed to the
function). However, the following would probably crash:
const void * Display(void) const { dCol = 6; return this; }
because it is attempting to modify memory that it very likely does not own,
which would probably cause an access violation or core dump.
I suppose it is possible that calling a method through an invalid pointer
may result in undefined behavior in some implementations, but on every
compiler I have used, class methods are always available and callable
through uninitialized and NULL pointers -- you just have no way of knowing
what will happen if you try to access memory through the 'this' pointer.
- Dennis