Virtual functions and inheritance
Tobias Pankrath via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Thu Jan 29 11:00:45 PST 2015
>
> This is almost the same code as written initially,
> let somone explain why the hell this is working:
>
> ---
> module test;
> import std.conv;
>
> class Parent {
> @property final string typeName() {
> return to!string(this);
> }
> }
>
> class Child : Parent {
> }
>
> void main() {
> auto p = new Parent;
> auto c = new Child;
> assert(p.typeName == __MODULE__ ~ ".Parent");
> assert(c.typeName == __MODULE__ ~ ".Child");
> }
> ---
Because to!string calls toString, which is a virtual function.
It's the same as the NVI-Idiom in C++.
More information about the Digitalmars-d-learn
mailing list