LearnFrenzy
Sign in Take a free test

Encapsulation · Predict the Output · Question 17

A constructor that refuses invalid input Answer, explanation & discussion

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

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

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

class Age {
    int v_;
public:
    explicit Age(int v) : v_(v) { if (v < 0 || v > 150) throw std::out_of_range("bad age"); }
    int value() const { return v_; }
};

int main() {
    std::vector<Age> ages;
    for (int raw : {25, -3, 40, 200, 0}) {
        try { ages.emplace_back(raw); }
        catch (const std::out_of_range&) { std::cout << 'x'; }
    }
    int sum = 0;
    for (const Age& a : ages) sum += a.value();
    std::cout << ' ' << ages.size() << ' ' << sum << '\n';
    return 0;
}
  • A xx 3 65 Correct
  • B 5 262
  • C xx 5 65
  • D x 4 265
Correct Answer: Option A

For −3 and 200 the constructor throws, so those Age objects are never created and never added. Every Age in the vector is valid: 25 + 40 + 0 = 65.

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