Sign In Start Free Trial
Account

Add to playlist

Create a Playlist

Modal Close icon
You need to login to use this feature.
  • Book Overview & Buying D Cookbook
  • Table Of Contents Toc
D Cookbook

D Cookbook

By : Adam Ruppe
5 (9)
close
close
D Cookbook

D Cookbook

5 (9)
By: Adam Ruppe

Overview of this book

Table of Contents (21 chapters)
close
close
D Cookbook
Credits
Foreword
About the Author
About the Reviewers
www.PacktPub.com
Preface
2
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...

Visually different images
CONTINUE READING
83
Tech Concepts
36
Programming languages
73
Tech Tools
Icon Unlimited access to the largest independent learning library in tech of over 8,000 expert-authored tech books and videos.
Icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Icon 50+ new titles added per month and exclusive early access to books as they are being written.
D Cookbook
notes
bookmark Notes and Bookmarks search Search in title playlist Add to playlist font-size Font size

Change the font size

margin-width Margin width

Change margin width

day-mode Day/Sepia/Night Modes

Change background colour

Close icon Search
Country selected

Close icon Your notes and bookmarks

Confirmation

Modal Close icon
claim successful

Buy this book with your credits?

Modal Close icon
Are you sure you want to buy this book with one of your credits?
Close
YES, BUY

Submit Your Feedback

Modal Close icon
Modal Close icon
Modal Close icon