LearnFrenzy
Sign in Take a free test

Encapsulation · Predict the Output · Question 4

An invariant broken through a leaked reference Answer, explanation & discussion

  • Output
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 4 Back to Exercise

What is the output of the following C++ program?

main.cpp
#include <iostream>
#include <vector>

class Primes {
    std::vector<int> v_{2, 3, 5};
public:
    bool add(int p) {
        for (int d = 2; d * d <= p; ++d) if (p % d == 0) return false;
        if (p < 2) return false;
        v_.push_back(p);
        return true;
    }
    std::vector<int>& data() { return v_; }
};

int main() {
    Primes p;
    std::cout << p.add(7) << p.add(9) << ' ';
    p.data().push_back(9);
    p.data()[0] = 4;
    for (int x : p.data()) std::cout << x << ' ';
    std::cout << '\n';
    return 0;
}
  • A 10 4 3 5 7 9 Correct
  • B 10 2 3 5 7
  • C 11 4 3 5 7 9
  • D 10 2 3 5 7 9
Correct Answer: Option A

add correctly rejects 9, but data() returns a non-const reference, so outside code adds 9 and replaces 2 with 4 – the "only primes" invariant is broken.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links