LearnFrenzy
Sign in Take a free test

Encapsulation · Predict the Output · Question 3

Modifying a copy returned by a getter Answer, explanation & discussion

  • Output
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 3 Back to Exercise

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

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

class User {
    std::string name_ = "asha";
public:
    std::string name_copy() const { return name_; }
    const std::string& name_ref() const { return name_; }
};

int main() {
    User u;
    std::string n = u.name_copy();
    n[0] = 'A';
    std::string m = u.name_ref();
    m += "!";
    std::cout << n << ' ' << m << ' ' << u.name_ref() << '\n';
    return 0;
}
  • A Asha asha! asha Correct
  • B Asha Asha! Asha
  • C asha asha! asha
  • D Compilation error
Correct Answer: Option A

Both n and m are separate strings (m is initialized from the const reference, which copies). Changing them never touches the private member.

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