Operator Overloading - Only for Classes and Structs?
Jonathan M Davis
newsgroup.d at jmdavisprog.com
Tue Jun 24 07:35:37 UTC 2025
On Monday, June 23, 2025 9:56:15 PM Mountain Daylight Time Andy Valencia via Digitalmars-d-learn wrote:
> I was a little surprised the subclassing syntax didn't do
> structural concatenation for struct's. That is,
>
> ```d
> import std.stdio : writeln;
>
> struct A {
> int a;
> void printA() {
> println(this.a);
> }
> }
> struct B : A {
> int b;
> void printAB() {
> this.printA();
> println(this.b);
> }
> }
>
> void an_A_fun(A arg) {
> arg.printA();
> }
>
> void main() {
> B foo;
> foo.a = 1;
> foo.b = 2;
> foo.printAB();
> an_A_fun(foo);
> }
> ```
>
> Unlike classes, this would guarantee storage adjacency, and still
> preserve its behavior as a value rather than an object reference.
> And then you get to share code for common initial parts of a
> given struct.
There has been talk of implementing something along those lines as a
replacement for `alias this`, since `alias this` has proven to be quite
problematic in practice (though we likely wouldn't actually remove `alias
this`, unfortunately, due to the desire to avoid breaking existing code).
However, it wouldn't have any sort of implicit conversion component as part
of it. It would just copy code from the "base" struct to the "derived"
struct as a way to share code. The idea would be to just copy code rather
than actually creating any sort of subtype.
What you've shown there with allowing a B to be passed as an A is called
object slicing, and avoiding that is one of the main reasons that structs
and classes were separated in D in the first place. It's a source of bugs in
C++.
- Jonathan M Davis
More information about the Digitalmars-d-learn
mailing list