← Back to Question List
C++ Code Walkthrough #66
Copying the Owner vs Copying the Viewer
📄 Code
Read carefully — what does this print?1#include <iostream>2using namespace std;34class Engine {5public:6 int hp;7 Engine(int h) : hp(h) {}8};910class Owner {11 Engine* m_engine;12public:13 Owner(int hp) { m_engine = new Engine(hp); }14 Owner(const Owner& other) { m_engine = new Engine(*other.m_engine); }15 ~Owner() { delete m_engine; }16 void tune(int extra) { m_engine->hp += extra; }17 int hp() const { return m_engine->hp; }18};1920class Viewer {21 Engine* m_engine;22public:23 Viewer(Engine* e) { m_engine = e; }24 void tune(int extra) { m_engine->hp += extra; }25 int hp() const { return m_engine->hp; }26};2728int main() {29 Owner o1(100);30 Owner o2 = o1;31 o2.tune(50);32 cout << o1.hp() << " " << o2.hp() << endl;3334 Engine shared(100);35 Viewer v1(&shared);36 Viewer v2 = v1;37 v2.tune(50);38 cout << v1.hp() << " " << v2.hp() << " " << shared.hp << endl;39 return 0;40}