Book Image

D Cookbook

By : Adam Ruppe
Book Image

D Cookbook

By: Adam Ruppe

Overview of this book

Table of Contents (21 chapters)
D Cookbook
Credits
Foreword
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Simulating inheritance with structs


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.

How to do it…

We will execute the following steps to simulate inheritance with structs:

  1. Write a struct to use as the base object type.

  2. Write the extended struct with a member of the base type.

  3. 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

How it works…

The alias this method is invoked in two places: if a member is requested and not found in the outer struct and if implicit conversion to a...