Project 11.12 Section 11 ⚡ Embedded Relevance: Core Encapsulation Composition Object Design Hardware Modeling

11.12 Modeling Hardware Subsystems using Class Encapsulation

Executive Summary: Demonstrating class encapsulation, private data invariants, and composition to model automotive subsystems.

💻 1. Annotated Source Code

#ifndef CAR_H
#define CAR_H

#include <string>
using namespace std;

class Car {
	public:
		Car(string color, int numDoors);
		string getColor() const;
		int getNumDoors() const;

	private:
		string color;
		int numDoors;
};

#endif
#include "Car.h"

Car::Car(string color, int numDoors) : color(color), numDoors(numDoors) {
}

string Car::getColor() const {
	return color;
}

int Car::getNumDoors() const {
	return numDoors;
}
#include <iostream>
#include "Car.h"

int main() {
	
	auto myCarPtr = make_unique<Car>("red", 4);

	cout << "Color: " << myCarPtr->getColor() << endl;
	cout << "Doors: " << myCarPtr->getNumDoors() << endl;


	return 0;
}

📐 2. Architecture & UML Class Model

📐 Car Class Encapsulation & Automotive Control State Model
+ Public - Private # Protected
<<class>> Car Vehicle Model
-make : std::string
-model : std::string
-year : int32_t
-speedMph : int32_t = 0
+Car(make: string, model: string, year: int)
+accelerate(amount: int) : void
+brake(amount: int) : void
+getSpeed() : int32_t const
+printCarDetails() : void const

📚 3. Core C++ Concepts Deep-Dive

Encapsulation & Invariants

Encapsulation ensures object state is modified only via validated member functions.

⚡ 4. Embedded Systems & Hardware Reality

Hardware Abstraction Layers (HAL)

Encapsulation models physical hardware modules (Engine Controller, Brake Actuator) cleanly.

💡 5. Production-Ready Embedded Refactoring

💡 Production-Ready Refactor
class MotorController {
public:
    void setPwmDuty(uint8_t duty) { duty_ = (duty > 100) ? 100 : duty; }
private:
    uint8_t duty_ = 0;
};

📝 Knowledge Verification Quiz

Test your understanding of the C++ concepts and embedded microcontroller trade-offs covered in this guide. Click any option for instant feedback.

Q1. Why is encapsulation critical in embedded device drivers?
A It hides register manipulation details and enforces valid hardware operating states.
B It increases clock speed.
C It converts variables to pointers.
D It prevents compiling.
Detailed Explanation: Encapsulation protects hardware registers from invalid bit states and restricts access to validated driver methods.