Aggregation, abstract classes and multiple inheritance
Clear, exam-focused notes on aggregation vs composition, abstract classes, and multiple inheritance: definitions, UML notation, language syntax (C++/Java/Python), diamond problem and solutions, with worked examples and common mistakes.
Drafted with Aria, reviewed by the AiCanCode.org team · Updated . How we write and check our notes. Spotted an error? Use Give Feedback at the bottom of the page.
Why it matters
Object modelling choices affect program design, reuse and correctness. Aggregation and composition decide object ownership and lifecycle in class models and UML diagrams; abstract classes and multiple inheritance affect how you express common behaviour and interfaces in code. Engineers use these ideas when designing class diagrams (in Analysis and Class design) and when implementing systems in C++, Java or Python.
Key ideas
Exact definition (university-style): "Let W and P be classes. W aggregates P if W has references to P objects to represent a whole/part relationship, and the lifecycle of P objects is independent of W." Draw: a class box W on the left, class box P on the right, a line with an open diamond at W's end. Label multiplicities (e.g. W 1 —<>— 0..* P).
Composition — a stronger form of aggregation where the whole owns the parts and controls their lifecycle: when the whole is destroyed, the parts are destroyed. UML uses a filled (black) diamond at the whole end. Exact definition: "Let W and P be classes. W composes P if each P instance is part of at most one W at a time and its lifetime depends on W: when the W is destroyed, its P parts are destroyed; a P cannot meaningfully exist independently of W. Creation may occur elsewhere, but once composed, the part’s lifetime is bound to the whole." Draw: W on left, P on right, line with filled diamond at W, multiplicities (W 1 —◆— 1..* P), and note creation/destruction arrows if needed.
Abstract class — a class that cannot be instantiated and is intended only to be subclassed. Exact definition: "A class A is abstract if it declares at least one operation without implementation (an abstract or pure virtual operation) or is marked abstract by the language; A cannot be constructed directly." Languages: C++ uses pure virtual functions; Java uses the
abstractkeyword; Python can use theabcmodule or raise NotImplementedError. Note: raising NotImplementedError does not make the class abstract or prevent instantiation; ABCs do.Pure virtual function (C++) — a virtual function declared with
= 0in its declaration. Exact statement: "A function declared asvirtual R f(...) = 0;in class C is pure virtual and makes C abstract; subclasses must provide an override unless they remain abstract." Note: a pure virtual function may still have a definition (callable via qualified name), but the class remains abstract. For interface-like bases, declare a virtual (usually defaulted) destructor. Assumption: compiler enforces non-instantiability.Interface — a type that specifies a set of operations with no (or limited default) implementation. In Java, an
interfaceis an abstract contract; interface fields are implicitly public static final, and methods are implicitly public abstract unless declareddefault,static, or (since Java 9)private. If multiple inherited interfaces provide the same default method, the class must override it (and may callI.super.m()to disambiguate). In C++ an abstract class with only pure virtual functions commonly acts as an interface; in Python a protocol or ABC acts similarly.Multiple inheritance — a feature of some languages where a class can inherit from more than one direct superclass. Exact statement: "A class D has multiple inheritance when D declares more than one immediate parent: class D : B, C { ... } (syntax varies by language)." Assumption: language supports name resolution rules to pick which parent method to use.
Diamond problem — an ambiguity that happens when class D inherits from B and C, and both B and C inherit from A. A's members may appear more than once in D unless the language provides rules or mechanisms (like virtual inheritance or MRO) to avoid duplication or ambiguity. State the problem: duplicated subobject or ambiguous method call resolution.
Virtual inheritance (C++) — a mechanism that ensures only one shared A subobject exists when B and C both inherit A virtually and D inherits B and C. Exact statement: "Declaring inheritance as
class B : virtual public Aensures B and C share one A when combined in a further derived class, preventing duplicate A subobjects." Compiler effect: layout and constructor rules change.Method Resolution Order (MRO, Python) — deterministic algorithm (C3 linearization) used by Python to produce a single order of classes to search for methods in multiple inheritance. Exact property: the MRO respects local precedence order and monotonicity and yields a linear order consistent with inheritance graph; Python's algorithm is C3 linearization. Tip: use
super()consistently so cooperative methods follow the MRO; avoid direct base calls unless intentionally breaking the cooperative chain.Liskov Substitution Principle (LSP) — a correctness law for subtyping: "If S is a subtype of T, then objects of type S must be usable anywhere objects of type T are expected, without altering desirable program properties (correctness, tasks, invariants)." Assumptions: behavioural subtyping; this is often checked by pre/postcondition and invariant reasoning.
Derivations universities ask for (example): Why composition implies stronger coupling than aggregation — step-by-step:
- Composition imposes lifecycle coupling: whole constructs/destroys parts.
- This makes parts dependent on whole's invariants (cannot be used elsewhere reliably).
- Therefore substitution or reuse of parts independently is harder than with aggregation.
- Conclusion: choose composition when parts have no meaning without whole; choose aggregation when parts can exist independently.
Diagrams to draw in an answer: 1) For aggregation: draw two boxes W and P, connect with a line, open diamond at W's end, multiplicities like 1 at W and 0..* at P. 2) For composition: same but filled diamond. 3) For diamond problem: draw A at top, B and C below both with arrows from A, and D below with arrows from B and C; mark ambiguity on members coming from A.
Formulas
C++ abstract (pure virtual): class A { virtual void f() = 0; }; — declares class A abstract; f is pure virtual.
Java abstract class: abstract class A { abstract void f(); } — declares abstract class and abstract method.
Java interface: interface I { void f(); } — interface; since Java 8 can have default implementations with default; interface fields are implicitly public static final and methods are implicitly public abstract unless declared otherwise.
Python ABC: from abc import ABC, abstractmethod; class A(ABC): @abstractmethod def f(self): pass — abstract base class.
UML aggregation notation: open-diamond at whole end (—<>—) — open diamond symbolises aggregation.
UML composition notation: filled-diamond at whole end (—◆—) — filled diamond symbolises composition.
C++ virtual inheritance: class B : virtual public A { ... }; — declares virtual inheritance to share A subobject.
Python MRO retrieval: D.__mro__ — shows linearized order (tuple) used to resolve methods.
Worked examples
- Modelling question (full-mark model answer)
Question: Draw UML for a
CarandWheelrelationship. Explain whether to use aggregation or composition. Answer steps:
- Reason: wheels usually do not exist meaningfully without the car (in many designs wheels can be removed but usually created/destroyed with the car). Prefer composition.
- Draw: Box
Carat left, boxWheelat right, a solid line with a filled diamond atCarend. Label multiplicities:Car 1 —◆— 4 Wheel. - State: Composition because
Carconstructs and destroysWheelobjects; removing the car implies wheels no longer are part of that car. If the system models wheels reused between cars, use aggregation (—<>—) and explain independence.
- C++ multiple inheritance and diamond problem (analysis answer) Code sketch and explanation:
- Suppose
class A { public: virtual void show() { cout<<"A"; } };thenclass B : public A { public: void show() override { cout<<"B";} }; class C : public A { public: void show() override { cout<<"C";} }; class D : public B, public C { }. - Problem: D now contains two A subobjects (one via B, one via C). Calling
D d; d.show();is ambiguous because the compiler cannot choose whether to call B::show or C::show. If you calld.B::show()it works; but an unqualifiedd.show()is ambiguous. - Fix with virtual inheritance: declare
class B : virtual public Aandclass C : virtual public A. Now B and C share a single A subobject, eliminating duplicate A state; however,D d; d.show();is still ambiguous unless D provides its own override or you qualify the call (e.g.,d.B::show()). Constructors change: the most-derived class constructs the virtual base A. (Draw the diamond to illustrate the shared A.)
- Python MRO example (trace) Code and trace:
- class A: def m(self): print('A')
- class B(A): def m(self): print('B')
- class C(A): def m(self): print('C')
- class D(B, C): pass
- Calling
D().m()printsBbecause Python computes MRO for D as (D, B, C, A, object) using C3 linearization and chooses the first match. - Explain: MRO ensures a consistent single linear order and prevents ambiguity; if B and C have conflicting implementations you can explicitly call a specific parent like
C.m(self).
Common mistakes
- Ignoring constructor rules for C++ virtual bases: virtual base is constructed by the most-derived class, not by intermediate bases — many forget this and expect B's constructor to initialize A.
- Treating abstract class and interface as identical: they differ (interfaces usually only specify operations; abstract classes can have state and non-abstract methods).
- In code examples, not qualifying ambiguous calls in multiple inheritance (C++), or not checking MRO (Python) — leads to compilation/runtime surprises.
For your exam
Question types you will see: definitions (state and explain aggregation/composition), short notes (compare aggregation and composition), diagram drawing (UML relationship boxes and diamonds), code snippets (C++/Java/Python demonstrating abstract classes or multiple inheritance and asking for output or error), and design questions (choose composition/aggregation and justify). What full-marks answers include:
- For definitions: a precise one-line definition plus a short example and UML notation.
- For diagrams: neat class boxes, labelled diamonds (open or filled), multiplicities, and a sentence explaining lifecycle consequences.
- For code questions: exact syntax, compile-time/ run-time behaviour, and mention language rules (e.g., C++ virtual inheritance, Java interfaces can't have instance fields).
- For design questions: state requirements, choose aggregation/composition with justification based on lifecycle and ownership, and show the UML.
Quick check
- What UML symbol denotes composition?
- How do you declare a pure virtual function in C++?
- What order does Python use to resolve methods in multiple inheritance?
Answers: 1) Filled (black) diamond at the whole end. 2)
virtual R f(...) = 0;in the class declaration. 3) C3 linearization (the MRO), shown byClass.__mro__.
Finished this topic? Mark it so your progress, study plan and readiness keep up.
Stuck on something here?