Virtual functions and inheritance
H. S. Teoh via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Mon Jan 26 21:03:31 PST 2015
On Tue, Jan 27, 2015 at 04:38:57AM +0000, David Monagle via Digitalmars-d-learn 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;
> }
> }
Try this:
class Parent {
@property string typeName() {
return typeid(this).toString();
}
}
> class Child : Parent {
> }
>
> void main() {
> auto p = new Parent;
> auto c = new Child;
> assert(p.typeName == "Parent");
> assert(p.typeName == "Child");
Bug: the second assert should have c.typeName. :-) But I got what you
mean.
> }
>
>
> 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?
typeof(this) is evaluated at compile-time. To get runtime information,
you need to use typeid().
Of course, with my suggested change your code still won't work as-is,
because typeid().toString() returns a fully-qualified name, so if your
source file is test.d, it would return "test.Parent" and "test.Child".
But you should be able to work with that. :-)
T
--
The volume of a pizza of thickness a and radius z can be described by
the following formula: pi zz a. -- Wouter Verhelst
More information about the Digitalmars-d-learn
mailing list