LearnFrenzy
Sign in Take a free test

Encapsulation · Find the Error · Question 9

Error: using a private nested enum outside the class Answer, explanation & discussion

  • Find the error
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 9 Back to Exercise

The program below does not compile. Which statement correctly describes the problem?

main.cpp
#include <iostream>

class Traffic {
    enum class Light { red, yellow, green };
    Light current_ = Light::red;
public:
    void next() { current_ = current_ == Light::red ? Light::green : current_ == Light::green ? Light::yellow : Light::red; }
};

int main() {
    Traffic t;
    t.next();
    Traffic::Light l = Traffic::Light::green;
    std::cout << (l == Traffic::Light::green) << '\n';
    return 0;
}
  • A enum class cannot be nested
  • B Light is declared in the private part of Traffic, so code outside the class cannot name it; make it public if users need it Correct
  • C next must return Light
  • D current_ must be public
Correct Answer: Option B

Private nested types are implementation details, just like private data.

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