If you could make any changes to D, what would they look like?

H. S. Teoh hsteoh at quickfur.ath.cx
Wed Oct 20 17:49:20 UTC 2021

On Wed, Oct 20, 2021 at 05:28:30PM +0000, Guillaume Piolat via Digitalmars-d wrote:
> One of the problem C++ has with objects-with-inheritance-as-value-type
> is "object slicing".
> It is ugly in theory: https://stackoverflow.com/a/14461532
> I guess it's one of the reason D doesn't have that, so a discussion
> about Object* needs to address that issue.

Yes, I believe the original reason D treats classes as inherently
by-reference is precisely because of this. Consider:

	class A {
		int x;
		virtual int getValue() { return x; }
	class B : A {
		int y;
		override int getValue() { return y; }

	B b;
	A a = b; // allowed since B is a subtype of A.
	writeln(a.getValue()); // uh oh

Assume by-value semantics for the sake of argument.  So `a` gets a copy
of part of B, because there is only enough space allocated on the stack
to store an A but not a B. So `y` is missing.  Then what should
a.getValue return?  Since it is virtual, it should call B.getValue,
which accesses a non-existent member, or in more practical terms, it
reads from the stack outside of the bounds of A.

All sorts of subtle (and nasty) problems crop up when you mix
polymorphic class objects with by-value semantics.  That's why D's
design makes more sense: if you want OO-style inheritance, let it be
by-reference all the way. If you want by-value semantics, which is
incompatible with OO-style polymorphism, use a struct.  Simple solution,
avoids all the nastiness you have to deal with in C++.


Never step over a puddle, always step around it. Chances are that whatever made it is still dripping.

More information about the Digitalmars-d mailing list