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

Three Files: Composition Across Headers

hardModular Programming

📄 Code

Read carefully — what does this print?
1// ===== Car.h =====
2#ifndef CAR_H
3#define CAR_H
4#include <iostream>
5#include <string>
6 
7class 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};
14 
15class 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};
23 
24#endif
25 
26// ===== Car.cpp =====
27#include <iostream>
28#include "Car.h"
29using namespace std;
30 
31Car::Car(const string& model, int hp) : m_model(model), m_engine(hp) {
32 cout << "Car " << m_model << endl;
33}
34 
35Car::~Car() {
36 cout << "~Car " << m_model << endl;
37}
38 
39void Car::show() const {
40 cout << m_model << " has " << m_engine.hp() << " hp" << endl;
41}
42 
43// ===== main.cpp =====
44#include <iostream>
45#include "Car.h"
46using namespace std;
47 
48int main() {
49 Car a("Civic", 158);
50 {
51 Car b("Golf", 147);
52 b.show();
53 }
54 a.show();
55 return 0;
56}

🎯 Your Answer