Composition vs. inheritance: Is it illegal in C++ to declare objects of one class as data members of another class? Choose the most accurate statement.
-
AIncorrect — it is legal and common (composition).
-
BCorrect — classes may only contain fundamental-type members.
-
CCorrect only if the member class has a default constructor.
-
DCorrect unless the member is declared as a pointer.
-
EIllegal when classes are unrelated by inheritance.
Answer
Correct Answer: Incorrect — it is legal and common (composition).
Explanation
Introduction / Context: This tests understanding of composition, a fundamental OO design technique where a class contains objects of other classes as members. C++ fully supports composition and relies on it for RAII and aggregation patterns. Declaring member objects is not only legal; it is idiomatic.
Given Data / Assumptions:
- Two user-defined class types exist.
- One class defines an object of the other class as a data member.
- Constructors and destructors follow normal C++ rules.
Concept / Approach: Composition embeds an object directly inside another object’s storage. Construction/destruction of member subobjects are automatically sequenced: members are constructed before the containing object’s body runs and destroyed in reverse order. Whether the member has a default constructor matters only for default-initialization; if it lacks one, you must initialize it explicitly in the owner’s member-initializer list. None of this makes composition illegal.
Step-by-Step Solution:
Declare class A and class B. Inside A, declare B b; or B b{args}; Ensure B is constructible using A’s constructor initializer list if needed.Verification / Alternative check: Try implementing a class that owns a std::string or std::vector. These are objects from the standard library; their presence as members exemplifies composition working seamlessly.
Why Other Options Are Wrong:
- “Only fundamental types allowed”: incorrect; user-defined types are normal members.
- “Only if default constructor exists”: you can initialize with parameters instead.
- “Must be pointer”: pointers are optional; direct members are common and safer.
- “Illegal if unrelated”: relationship is irrelevant; composition does not require inheritance.
Common Pitfalls: Forgetting to initialize non-default-constructible members in the initializer list; assuming composition implies ownership semantics identical to pointers (RAII usually makes it safer).
Final Answer: Incorrect — it is legal and common (composition).