CJCoding With Joseph
15free / daySign inCreate account
← Back to Question List
C++ Code Walkthrough #96

Member Functions Defined Outside the Template

mediumTemplates

📄 Code

Read carefully — what does this print?
1#include <iostream>
2#include <string>
3 
4template <typename T>
5class Box {
6 T m_value;
7public:
8 Box(T value);
9 T get() const;
10 void set(T value);
11 void show() const;
12};
13 
14template <typename T>
15Box<T>::Box(T value) : m_value(value) {
16 std::cout << "Box made\n";
17}
18 
19template <typename T>
20T Box<T>::get() const {
21 return m_value;
22}
23 
24template <typename T>
25void Box<T>::set(T value) {
26 m_value = value;
27}
28 
29template <typename T>
30void Box<T>::show() const {
31 std::cout << "Box holds " << m_value << "\n";
32}
33 
34int main() {
35 Box<int> a(5);
36 Box<std::string> b("cat");
37 a.set(a.get() * 2);
38 b.set(b.get() + "s");
39 a.show();
40 b.show();
41 std::cout << a.get() + 1 << "\n";
42 return 0;
43}

🎯 Your Answer