Class inheritance can be broken up into three concepts: subtyping, composition, and polymorphism. With alias this
, subtyping and composition are easy, providing a nonpolymorphic type of inheritance.
We will execute the following steps to simulate inheritance with structs:
Write a struct to use as the base object type.
Write the extended struct with a member of the base type.
Use
alias this
with the base type to allow easy access to base members and implicit conversion.
The code is as follows:
struct Base { int x; int y; } struct Derived { int dx; int dy; Base base; // a member of the base type - composition alias base this; // then use alias this for subtyping } void operateOnBase(Base base) {} void operateOnDerived(Derived derived) {} Derived d; operateOnBase(d); // works