Multiple inheritance

On this page 8

Multiple inheritance is a feature of object-oriented programming in which a single class derives from two or more base classes at once, inheriting the fields, methods and type identity of each parent. It extends ordinary single inheritance from a tree of classes into a directed acyclic graph, which makes reuse more flexible but forces the language to answer a hard question: which parent wins when two of them define the same member.

Languages handle that question very differently. C++ supports full multiple inheritance of implementation, Python supports it with a deterministic method resolution order, while Java and C# allow multiple inheritance only of interfaces. Understanding these choices explains much of the design of modern programming languages and why many teams prefer composition or traits instead.

How multiple inheritance builds a class graph

Under multiple inheritance, a derived class lists several direct base classes, and every member of every base becomes reachable through the derived class unless it is overridden. The resulting hierarchy is no longer a tree, because one class can have several parents and two parents can share a common ancestor. The compiler or runtime must therefore define a lookup order for names and a memory layout for objects.

In a statically compiled language such as C++, an object of the derived class physically contains a subobject for each base class. Converting a pointer to the second base requires an implicit pointer adjustment, because that subobject does not start at the same address as the full object. Virtual function calls through the second base use additional virtual tables or thunks that correct the this pointer before the call.

The table below summarizes the elements a language must define once a class can have more than one parent.

MechanismPurposeTypical implementation
Name lookup orderDecides which inherited member is usedLinearization or explicit qualification
Object layoutPlaces each base subobject in memorySequential subobjects with offsets
Pointer adjustmentConverts derived pointers to base pointersCompile-time offset or runtime offset
Dispatch tablesSupports overriding across several basesOne virtual table per polymorphic base
Constructor orderInitializes every base exactly onceDeclaration order, virtual bases first
Core mechanisms behind multiple inheritance

The diamond problem and ambiguity

The diamond problem arises when a class inherits from two classes that both derive from the same ancestor, so the ancestor appears twice in the graph. Two questions follow immediately: does the final object hold one copy or two copies of the ancestor state, and which version of an overridden method should a call reach. Without a rule, the program is ambiguous and cannot be compiled or executed predictably.

C++ answers the first question with virtual inheritance, which tells the compiler to share a single ancestor subobject among all paths. The price is an extra level of indirection, a virtual base pointer or offset, and the rule that the most derived class constructs the virtual base directly. For the second question, C++ reports an error when two paths supply different final overriders, and the programmer must override the method in the derived class or qualify the call explicitly.

Python takes a different route. It computes the C3 linearization, a single ordered list of all ancestors called the method resolution order (MRO). Every class appears once, children come before parents, and the local order of base classes is preserved. Cooperative calls through super() follow this list, so each ancestor method runs exactly once even in a diamond.

Language support compared

Mainstream languages fall into a few clear camps, and the differences shape how libraries and frameworks are designed in each ecosystem. The comparison below covers the most common choices.

LanguageMultiple implementation inheritanceConflict resolution
C++Yes, full supportExplicit qualification, virtual bases
PythonYes, full supportC3 linearization and super()
EiffelYes, full supportRenaming and selection clauses
JavaNo, interfaces onlyDefault methods must be overridden on conflict
C#No, interfaces onlyExplicit interface implementation
ScalaThrough traitsLinearization of mixed-in traits
RustNo class inheritanceTraits with explicit disambiguation syntax
How major languages treat multiple inheritance

Since Java 8, default methods in interfaces allow limited inheritance of behavior, but not of state. When two interfaces supply the same default method, the implementing class must override it and may call a specific parent with the Interface.super.method() form. This design keeps the useful part of multiple inheritance while avoiding duplicated instance fields.

Several neighboring techniques solve the same reuse problem with fewer risks, and choosing among them is a frequent design decision. Interfaces share contracts without implementation, mixins add small units of behavior, traits add behavior with explicit conflict rules, and composition delegates work to contained objects.

TechniqueShares stateShares implementationMain risk
Multiple inheritanceYesYesAmbiguity and fragile hierarchies
Interface inheritanceNoLimited, via default methodsBoilerplate in implementations
MixinSometimesYesHidden ordering dependencies
TraitUsually noYesConflicts require manual resolution
CompositionThrough membersThrough delegationForwarding code and indirection
Alternatives for combining behavior from several sources

The principle of composition over inheritance grew partly from experience with deep multiple inheritance graphs. Delegation keeps each component independently testable, while inheritance couples the derived class to implementation details of every parent. In practice, mixins in Python and traits in Scala are disciplined forms of multiple inheritance rather than a complete rejection of it.

When multiple inheritance is the right choice

Multiple inheritance works best when each parent represents an independent, orthogonal capability and the parents share little or no state. Typical successful uses include adding logging, serialization or comparison support to domain classes, and implementing several abstract interfaces in C++ through pure abstract base classes.

SituationRecommended approachReason
Several pure contractsInherit from abstract interfacesNo state, no layout conflict
Small reusable behaviorsUse mixins or traitsClear intent, limited coupling
Shared ancestor with statePrefer compositionAvoids diamond complexity
Two full concrete classesAvoid inheritanceHigh risk of conflicting invariants
Framework requires base classesFollow the framework MRO rulesCooperative super() calls expected
Decision guide for using multiple inheritance

Limitations and common mistakes

The most serious drawback is conceptual complexity: a reader must understand every ancestor and the resolution order to predict what a single method call does. Changes to a distant base class can silently alter behavior, a form of the fragile base class problem that multiplies with each additional parent.

  • Inheriting from two concrete classes with overlapping state, which produces duplicated or inconsistent fields.
  • Forgetting virtual inheritance in a C++ diamond, which creates two ancestor subobjects and ambiguous conversions.
  • Calling parent methods by name instead of through cooperative `super()` in Python, which runs an ancestor twice or skips one.
  • Using C-style casts across a multiple inheritance graph, which can skip the required pointer adjustment.
  • Building hierarchies only for code reuse when no genuine is-a relationship exists.

Performance costs are usually modest but real: extra virtual table pointers increase object size, and calls through a secondary base may pass through an adjustor thunk. In most applications these costs matter far less than the maintenance burden of an unclear hierarchy.

Stripped to the essentials

Multiple inheritance means a new kind of object can take features from several parents at once. Imagine a smartphone that is both a camera and a telephone: it inherits picture taking from one family and calling from another.

The trouble starts when both parents have a feature with the same name, such as a power button. The language needs a clear rule about which one to use, or the result is confusing. Some languages provide such rules, while others allow only one real parent plus any number of promises about behavior.

Where it is applied

A team building a web application in Python uses a popular web framework whose views are assembled from small mixin classes. A view that shows an order list inherits from a login check mixin, a permission mixin and a generic list view, in that order. Python computes the method resolution order, so each request first verifies the session, then checks permissions, and only then queries the database.

Because every mixin calls super() cooperatively, the team adds a new auditing mixin to forty views by inserting one base class per view, without touching the underlying list logic. The outcome is consistent access control across the application with very little duplicated code. When a developer once placed the list view before the login mixin, anonymous users briefly saw data in testing, which taught the team that base class order is part of the security design.