Difficulty: Easy
Correct Answer: Composition
Explanation:
Introduction:
There are several ways to reuse code in C++. This question focuses on the pattern where one class holds other objects as members and delegates behavior to them—an approach often summarized as “has-a”.
Given Data / Assumptions:
Concept / Approach:
Composition means a class contains objects of other classes as data members and uses them to implement behavior. It is the backbone of “composition over inheritance”: prefer assembling behavior from parts rather than extending a base class when an is-a relationship does not truly exist.
Step-by-Step Solution:
1) Identify responsibilities that can be delegated to collaborators (e.g., Logger, Repository).2) Add collaborators as members and initialize them via constructors or setters.3) Forward calls to these members to achieve the desired behavior.4) Enjoy improved substitution and unit testing by mocking or swapping components.
Verification / Alternative check:
Refactor an inheritance-heavy design to composition and observe reduced coupling and fewer fragile base class problems.
Why Other Options Are Wrong:
Encapsulation: hiding internal details; orthogonal to how you assemble types.Abstraction: modeling essential behavior; not specifically a containment mechanism.Inheritance: reuses base implementation but creates tight is-a relationships.
Common Pitfalls:
Overusing inheritance for code reuse, leading to rigid hierarchies. Composition typically provides better flexibility and testability.
Final Answer:
Composition
Discussion & Comments