Virtual functions and inheritance
Baz via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Thu Jan 29 10:45:23 PST 2015
On Tuesday, 27 January 2015 at 04:38:59 UTC, David Monagle wrote:
> Hi guys,
>
> I'm a former C++ developer and really enjoying working with D
> now. I have a question that I hope some of you may be able to
> answer.
>
> class Parent {
> @property string typeName() {
> return typeof(this).stringof;
> }
> }
>
> class Child : Parent {
> }
>
> void main() {
> auto p = new Parent;
> auto c = new Child;
> assert(p.typeName == "Parent");
> assert(p.typeName == "Child");
> }
>
>
> I'm looking for an explanation as to why this doesn't work,
> then a suggestion for how I may achieve child classes being
> able to generate a string description of their own type,
> without redefining the typeName property on each child. (I'm
> currently solving this with a mixin, but I was hoping for a
> better solution.
>
> I'm assuming it doesn't work because either typeof(this) or
> .stringof is evaluated at compile time?
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");
}
---
More information about the Digitalmars-d-learn
mailing list