Search code examples
classinheritanced

Overriding non-function class members in D


Is there a way, in DLang, to override class fields that aren't functions in a derived class? Or do class vtables only contain function pointers?

For instance, I'd like the following to print "bar", but it prints "foo".

class Foo
{
   string s = "foo";
}

class Bar : Foo
{
   string s = "bar";
}

void main()
{
   import std.stdio;

   Foo bar = new Bar;
   writeln(bar.s);
}

Solution

  • Only functions can be virtual. The vtable provides a way to look up the correct override for a function, but the variables are accessed directly without any indirections like you get when using a virtual table.

    If you want to do something similar to overriding a member variable, then the closest you're going to get is a property function. e.g.

    class Foo
    {
        @property string s() { return _s; }
    
        private string _s = "foo";
    }
    
    class Bar : Foo
    {
        override @property string s() { return _s; }
    
        private string _s = "bar";
    }
    
    void main()
    {
        import std.stdio;
    
        Foo bar = new Bar;
        writeln(bar.s);
    }