← Back to Question List
C++ Code Walkthrough #80
Three Files: Composition Across Headers
📄 Code
Read carefully — what does this print?1// ===== Car.h =====2#ifndef CAR_H3#define CAR_H4#include <iostream>5#include <string>67class Engine {8 int m_hp;9public:10 Engine(int hp) : m_hp(hp) { std::cout << "Engine " << m_hp << std::endl; }11 ~Engine() { std::cout << "~Engine " << m_hp << std::endl; }12 int hp() const { return m_hp; }13};1415class Car {16 std::string m_model;17 Engine m_engine;18public:19 Car(const std::string& model, int hp);20 ~Car();21 void show() const;22};2324#endif2526// ===== Car.cpp =====27#include <iostream>28#include "Car.h"29using namespace std;3031Car::Car(const string& model, int hp) : m_model(model), m_engine(hp) {32 cout << "Car " << m_model << endl;33}3435Car::~Car() {36 cout << "~Car " << m_model << endl;37}3839void Car::show() const {40 cout << m_model << " has " << m_engine.hp() << " hp" << endl;41}4243// ===== main.cpp =====44#include <iostream>45#include "Car.h"46using namespace std;4748int main() {49 Car a("Civic", 158);50 {51 Car b("Golf", 147);52 b.show();53 }54 a.show();55 return 0;56}