CJCoding With Joseph
15free / daySign inCreate account
← Back to Question List

Select topics to narrow your question pool, then enable Random to jump to a random question matching your filters.

Topics:
C++ Quiz #131

Returning a Copy or a Reference From Box

hardTemplates

get() returns T by value and peek() returns const T&. After b.set("bye"), what is printed?

📄 Code

1#include <iostream>
2#include <string>
3 
4template <typename T>
5class Box {
6 T value;
7public:
8 Box(T v) : value(v) {}
9 T get() const { return value; }
10 const T& peek() const { return value; }
11 void set(T v) { value = v; }
12};
13 
14int main() {
15 Box<std::string> b("hello");
16 std::string copy = b.get();
17 const std::string& ref = b.peek();
18 b.set("bye");
19 std::cout << copy << " " << ref << "\n";
20 return 0;
21}