Hello all,

TDPL gives a description in Section 6.13 (pp. 230-233) of a method for subtyping by storing a private instance of the base type and using "alias ... this" to access its methods. The example given is as follows:

class StorableShape : Shape
{
    private DBObject _store;
    alias _store this;

    this()
    {
        _store = new DBObject;
    }
}

However, I've found that this won't work because the "private" keyword means that functions and objects outside the module won't be able to access the public methods of _store, even though the alias itself is public.

I've attached a small example with 2 classes, A and B, where B stores an internal copy of A in a similar manner. In this case, if you run rdmd inherit.d, you'll get an error:

  inherit.d(8): Error: class inheritance.B member base is not accessible

Is this a bug, or intentional, and if it's intentional, how can one make the public methods of the "base" class accessible while keeping the instance private?

Thanks & best wishes,

    -- Joe
import std.stdio;
import inheritance;

void main()
{
    auto b = new B(5, 10);
    writeln(b.varProd());
    writeln(b.varSum());
}
module inheritance;

final class A
{
  private:
    int _a;
    int _b;

  public:
    this(int a, int b)
    {
        _a = a;
        _b = b;
    }

    int varSum()
    {
        return _a + _b;
    }
}

final class B
{
  private A base;

  alias base this;

  this(int a, int b)
  {
      base = new A(a, b);
  }

  int varProd()
  {
      return _a * _b;
  }
}

Reply via email to