Thread overview
Null Object works still fine
Aug 11, 2012
Namespace
Aug 11, 2012
Adam D. Ruppe
Aug 11, 2012
David Nadlinger
Aug 11, 2012
Marco Leise
August 11, 2012
This code works fine but it shouldn't, or?

http://dpaste.dzfl.pl/b9027fff
August 11, 2012
On Saturday, 11 August 2012 at 22:23:12 UTC, Namespace wrote:
> This code works fine but it shouldn't, or?


The reason is the print method is private, which means it is also automatically final and doesn't access any member variables. Since it doesn't access members, it doesn't actually try to use the object and thus works ok.

(You can access private methods as long as you are still in the same module, so this is by design too.)

It being final is important because it means it is just a regular function - it doesn't need to access the object's virtual function table either.


If it was a public final method, it would say "AssertEerror: null this", but since it is private I think that check is intentionally left out.



But what you have here is everything working right, but the rule might seem weird... it's just because you aren't actually accessing the object, so the fact that it is null never comes into play.

August 11, 2012
On Saturday, 11 August 2012 at 22:23:12 UTC, Namespace wrote:
> This code works fine but it shouldn't, or?
>
> http://dpaste.dzfl.pl/b9027fff

You don't actually dereference ›this‹ in print(), so the null value in the implicit this parameter doesn't matter.

David
August 11, 2012
Am Sun, 12 Aug 2012 00:23:10 +0200
schrieb "Namespace" <rswhite4@googlemail.com>:

> This code works fine but it shouldn't, or?
> 
> http://dpaste.dzfl.pl/b9027fff

That's fine. There is no check for null at every possible occasion, like I think in Java. The operating system will catch any actual null dereference though, by notifying you of an invalid memory access.
So in other words, D uses the fast approach.

Cases where your print will not work is, when print() is a virtual method of that class (one that can be overridden). That would need to actually dereference the object to take a look into the virtual method table.
'private' and 'final' methods (or methods of a 'final class') are not virtual.

-- 
Marco