LearnFrenzy
Sign in Take a free test

Encapsulation · Find the Error · Question 2

Error: modifying data through a const reference getter Answer, explanation & discussion

  • Find the error
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 2 Back to Exercise

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

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

class Team {
    std::vector<std::string> members_{"Asha"};
public:
    const std::vector<std::string>& members() const { return members_; }
};

int main() {
    Team t;
    t.members().push_back("Ravi");
    std::cout << t.members().size() << '\n';
    return 0;
}
  • A <string> is not included
  • B members() returns a const reference, so push_back (a non-const member) cannot be called on it – the class deliberately offers read-only access Correct
  • C members_ must be public
  • D Team needs a constructor
Correct Answer: Option B

Add a member function such as add_member(name) that validates and inserts.

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