January 29, 2015 Re: Virtual functions and inheritance | ||||
---|---|---|---|---|
| ||||
Posted in reply to Baz | >
> 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++.
|
Copyright © 1999-2021 by the D Language Foundation