LearnFrenzy
Sign in Take a free test

Encapsulation · Predict the Output · Question 13

Reading private data through a std::span view Answer, explanation & discussion

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

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

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

class Playlist {
    std::vector<int> durations_{210, 185, 240};
public:
    std::span<const int> durations() const { return durations_; }
    void add(int sec) { if (sec > 0) durations_.push_back(sec); }
};

int main() {
    Playlist p;
    p.add(-5);
    p.add(150);
    int total = 0;
    for (int d : p.durations()) total += d;
    std::cout << p.durations().size() << ' ' << total / 60 << ':' << total % 60 << '\n';
    return 0;
}
  • A 4 13:5 Correct
  • B 5 12:60
  • C 4 13:05
  • D 3 10:35
Correct Answer: Option A

−5 is rejected; 150 is added, giving 4 songs totalling 785 seconds = 13 min 5 s. The span lets callers read, never modify, the durations.

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