Improvement to struct inheritance possible?
Meta
jared771 at gmail.com
Thu Jan 18 20:43:30 UTC 2024
On Thursday, 18 January 2024 at 07:10:49 UTC, Danilo wrote:
> The following code does not work, and I think it may be a bug
> or could need an enhancement:
>
> ```d
> module app;
> import std;
>
> void main() {
> auto x = new Derived(10, 20);
> }
>
> struct Base {
> int a;
> }
>
> struct Derived
> {
> Base base;
> int b;
> alias this = base;
>
> @disable this();
>
> // `a` is not available for use with constructor parameters.
> //
> this( typeof(a) _a, typeof(b) _b ) {
> //
> // inside the body of the constructor, `a` is available!
> //
> a = _a;
> b = _b;
>
> writeln( a, ", ", b );
> }
> }
> ```
>
> The use of `typeof(a)` as a constructor parameter gives:
> Error: undefined identifier `a`
>
> Instead I have to explicitely use:
> ```d
> this( typeof(this.a) _a, typeof(b) _b )
> // or
> this( typeof(base.a) _a, typeof(b) _b )
> ```
>
> I think this may be a bug, because `base` was imported into the
> scope using `alias this = base` and should therefore be
> available as plain `a`.
>
> With class inheritance everything works as expected:
> ```d
> module app;
>
> import std;
>
> class A {
> int x;
> }
>
> class B : A {
> int y;
> }
>
> class C : B {
> int z;
>
> this( typeof(x) _x, typeof(y) _y, typeof(z) _z) {
> writeln(
> _x, ", ",
> _y, ", ",
> _z
> );
> }
> }
>
> void main() {
> new C(10, 20, 30);
> }
> ```
>
> Could this please get improved a little bit, so "inherited"
> structure members using `alias this` are already available for
> constructor paramaters?
>
> Thanks!
This won't work because `alias this` is not inheritance ini the
object oriented, class-based sense. All it does is when you try
to access a symbol through a Derived struct (e.g. `Derived d;
writeln(d.a);`) that the compiler sees does not exist in Derived,
it will rewrite that to `Derived d; writeln(d.base.a);` (and also
when you pass a Derived to a method taking a Base, it will
automatically be rewritten to pass the Derived struct's Base
member to the method instead).
You really cannot think of `alias this` as inheritance, because
it is not at all the same as the object-oriented concept of
inheritance. You'll only run into problems thinking of it that
way.
More information about the Digitalmars-d
mailing list