Skip to content

Quiz 9 — Composition and Association

Ten questions on who owns what. Almost every question is really "what is the lifetime rule here?".

Attempt all of them closed-book, then mark yourself against the answers.

Concepts: composition · aggregation · association · ownership · member lifetime · dangling references.


Q1. (MCQ) In which relationship does the part outlive the whole?

  • A. composition
  • B. aggregation
  • C. neither
  • D. both

Q2. (true/false) In composition, destroying the whole destroys the part.

Q3. (multiple-select) Which of these are usually aggregation (the part exists independently)? Select all that apply.

  • A. A playlist and the songs in a shared music library
  • B. A car and its engine
  • C. A team and the players
  • D. A document and its own text buffer

Q4. (predict) Write the output in order.

#include <iostream>

class Part {
public:
    explicit Part(char id) : id_(id) { std::cout << "make " << id_ << '\n'; }
    ~Part() { std::cout << "drop " << id_ << '\n'; }
private:
    char id_;
};

class Machine {
public:
    Machine() : first_('A'), second_('B') { std::cout << "ready\n"; }
    ~Machine() { std::cout << "gone\n"; }
private:
    Part first_;
    Part second_;
};

int main() {
    Machine m;
}

Q5. (debug) A room stores who is present, but the entries dangle. Explain when the problem occurs and how to fix the design.

#include <string>
#include <vector>

class Member {
public:
    explicit Member(std::string name) : name_(name) {}
    std::string name() const { return name_; }
private:
    std::string name_;
};

class ReadingRoom {
public:
    void checkIn(Member& m) { present_.push_back(&m); }
private:
    std::vector<Member*> present_;
};

Q6. (analysis) For each pair, say composition, aggregation or association: a car and its engine; a doctor and an appointment; a course and its lecturer.

Q7. (predict) Write the output, in order.

#include <iostream>

class A { public: A() { std::cout << "A+ "; } ~A() { std::cout << "A- "; } };
class B { public: B() { std::cout << "B+ "; } ~B() { std::cout << "B- "; } };

class Owner {
public:
    Owner() : a_(), b_() { std::cout << "O+ "; }
    ~Owner() { std::cout << "O- "; }
private:
    A a_;
    B b_;
};

int main() {
    Owner o;
}

Q8. (short answer) What does it mean to say one object owns another? Answer in terms of lifetime, not of memory syntax.

Q9. (design) Students register for courses; a course has a capacity; registrations know which student and course they refer to; students and courses outlive registrations. State each relationship and the one operation that enforces the capacity.

Q10. (analysis) Two classes each hold the other by value. Explain why this cannot compile, and name two ways to break the cycle.


Scoring: mark yourself with the answers, then read the self-assessment guide.