Cover by Alex Payne, Dean Wampler

Safari, the world’s most comprehensive technology and business learning platform.

Find the exact information you need to solve a problem on the fly, or go deeper to master the technologies and skills you need to succeed

Start Free Trial

No credit card required

O'Reilly logo

Effective Design of Traits

One of the reasons that many languages (like Java) do not implement multiple inheritance is because of the problems observed with multiple inheritance in C++. One of those problems is the so-called diamond of death, which is illustrated in Figure 13-1.

Diamond of death in languages with multiple inheritance

Figure 13-1. Diamond of death in languages with multiple inheritance

In C++, each constructor for C will invoke a constructor for B1 and a constructor for B2 (explicitly or implicitly). Each constructor for B1 and B2 will invoke a constructor for A. Hence, in a naïve implementation of multiple inheritance, the fields of A, a1 and a2, could be initialized twice and possibly initialized in an inconsistent way or there might be two different A “pieces” in the C instance, one for B1 and one for B2! C++ has mechanisms to clarify what should happen, but it’s up to the developer to understand the details and to do the correct thing.

Scala’s single inheritance and support for traits avoid these problems, while providing the most important benefit of multiple inheritance: mixin composition. The order of construction is unambiguous (see Linearization of an Object’s Hierarchy). Traits can’t have constructor argument lists, but Scala ensures that their fields are properly initialized when instances are created, as we saw in Constructing Traits and Overriding Abstract and Concrete Fields in Traits. We saw another example ...

Find the exact information you need to solve a problem on the fly, or go deeper to master the technologies and skills you need to succeed

Start Free Trial

No credit card required