Question 3
Back to Exercise
What is the output of the following C++ program?
#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!