Newbie: Inheritance & slicing problem

Larry Luther larry.luther at dolby.com
Wed Jun 2 10:47:35 PDT 2010


"Steven Schveighoffer" <schveiguy at yahoo.com> wrote in message 
news:op.vddvhs17eav7ka at localhost.localdomain...
| On Thu, 27 May 2010 17:04:35 -0400, Larry Luther <larry.luther at dolby.com>
| wrote:
|
| > "bearophile" <bearophileHUGS at lycos.com> wrote in message
| > news:ht4krg$17l9$1 at digitalmars.com...
| > | On the base of your long experience do you like D so far?
| >
| > There are many things that I like and I strongly agree with the failings
| > of C++ mentioned in the docs.  I don't like the asymmetry between 
structs
| > and classes.  I don't see why structs can't have inheritance.
|
| Because of the slicing problem.  It's basically something like this:
|
| struct A {virtual void foo();};
|
| struct B : A {virtual void foo();};
|
| void bar(A a)
| {
|   a.foo();
| }
|
| void baz()
| {
|   B b;
|   bar(b); // b is "sliced" down to an A, and bar will now call A.foo
| instead of the expected B.foo.
| }
|
| The really bad part about this is, b might have set up its private
| variables so that to call A.foo would cause an error.
|
| Same thing happens when returning by value.  The general issue is that
| inheritance and value types don't mix.  But reference types (that is,
| types that are always passed by reference) never have the slicing
| problem.  So classes in D (which are reference types) can inherit, while
| structs (which *can be* value types) cannot inherit.  I have hoped that at
| some point, structs can be auto-composed, without a vtable, but you still
| have to do this manually.  Luckily, it's not so much of a chore now that
| alias this is around.
...

I have verified the slicing problem within C++.
The problem disappears (in accordance with your statements) if "bar"
is declared such that it's argument is passed by reference.
The bottom line is that C++ overcame this sufficiently to allow
inheritance for structs. 




More information about the Digitalmars-d-learn mailing list