Why can't I inherit (extend) structs?
Jarrett Billingsley
kb3ctd2 at yahoo.com
Wed Oct 11 13:05:58 PDT 2006
"rm" <roel.mathys at gmail.com> wrote in message
news:egj6fb$1ih4$1 at digitaldaemon.com...
> why do you say correct order?
It matters when you're dealing with system libraries that expect structures
to be laid out in a certain way, and it matters if you want to have type
polymorphism (i.e. casting a pointer to a derived structure to a base
structure type). I.e.
template BaseMembers()
{
int x;
}
template DerivedMembers()
{
int y;
}
struct Base
{
mixin BaseMembers;
}
struct Derived
{
mixin DerivedMembers; // oops! wrong order
mixin BaseMembers;
}
void main()
{
Derived d;
d.x = 3;
d.y = 4;
Base* b = cast(Base*)&d;
writefln(b.x); // prints "4", not "3"
}
The compiler can't complain about something like this because it doesn't
know anything about deriving structs and keeping their members in the
correct order in memory. With the ability to derive structs, the problem
just goes away.
More information about the Digitalmars-d-learn
mailing list