Skip to content

Quiz 4 — Encapsulation

Ten questions on invariants, access control, and the ways a class can leak. Several questions show code that looks encapsulated but is not.

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

Concepts: invariant · access control · accessors and mutators · leaking a reference · const-correctness.


Q1. (MCQ) What is an invariant?

  • A. A value that never changes
  • B. A statement that must be true of an object for its whole lifetime
  • C. A member function that is const
  • D. A rule enforced only in the constructor

Q2. (true/false) A class with private data and a getter that returns a & to that data is fully encapsulated.

Q3. (multiple-select) Which of these break encapsulation? Select all that apply.

  • A. A public data member
  • B. An accessor returning const std::string&
  • C. An accessor returning std::string& to a private member
  • D. A setter that accepts any value of the right type

Q4. (predict) What does this print, and what invariant did the class intend?

#include <iostream>
#include <vector>

class Team {
public:
    void add(int strength) {
        if (strength > 0) members_.push_back(strength);
    }
    std::vector<int>& members() { return members_; }
    int total() const {
        int sum = 0;
        for (int s : members_) sum += s;
        return sum;
    }
private:
    std::vector<int> members_;
};

int main() {
    Team t;
    t.add(5);
    t.add(8);
    t.members().push_back(-100);
    std::cout << t.total() << '\n';
}

Q5. (debug) Repair Team above so the invariant holds even against a hostile caller, without removing the ability to inspect the members.

Q6. (analysis) Explain, in one sentence, why enforcing an invariant in one place is better than asking every caller to respect a rule.

Q7. (short answer) Name one thing encapsulation makes impossible, rather than merely discouraged.

Q8. (predict) Does this compile? If not, what is the problem?

#include <iostream>

class Session {
public:
    Session(int minutes) : minutes_(minutes) {}
    int& minutes() { return minutes_; }
    int  minutes() const { return minutes_; }
private:
    int minutes_;
};

int main() {
    Session s{30};
    s.minutes() = -5;
    std::cout << s.minutes() << '\n';
}

Q9. (design) A booking slot must have a start hour between 0 and 23 and a duration between 15 and 120 minutes. State the invariant, the one place that enforces it, and the mechanism you would use to reject a bad value.

Q10. (analysis) A colleague says "an accessor and a mutator for every field is encapsulation." Give one example where that claim is false for a class with two related fields.


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