Skip to content

Instantly share code, notes, and snippets.

@kenpower
Created February 4, 2026 14:40
Show Gist options
  • Select an option

  • Save kenpower/bb0b2feb8b3765b85c09db82c4207d7d to your computer and use it in GitHub Desktop.

Select an option

Save kenpower/bb0b2feb8b3765b85c09db82c4207d7d to your computer and use it in GitHub Desktop.
smart pointer v old pointer DI
#include <iostream>
#include <memory>
// Interface
class Engine {
public:
virtual ~Engine() = default;
virtual void start() = 0;
virtual int getHorsepower() const = 0;
};
// Concrete implementations
class V6Engine : public Engine {
public:
void start() override {
std::cout << "V6 engine starting with a smooth hum..." << std::endl;
}
int getHorsepower() const override { return 280; }
};
class V8Engine : public Engine {
public:
void start() override {
std::cout << "V8 engine roaring to life!" << std::endl;
}
int getHorsepower() const override { return 450; }
};
// ===== RAW POINTER VERSION =====
class Car {
private:
Engine* engine;
std::string model;
public:
// Constructor - can accept nullptr
Car(const std::string& model)
: model(model) {
}
void setEngine(Engine* newEngine) {
engine = newEngine;
}
void startCar() {
std::cout << model << " attempting to start..." << std::endl;
if (engine == nullptr) {
std::cout << "ERROR: No engine installed!" << std::endl;
return;
}
engine->start();
std::cout << "Power: " << engine->getHorsepower() << " HP"
<< std::endl;
}
};
// ===== SMART POINTER VERSION =====
class SmartCar {
private:
std::unique_ptr<Engine> engine = nullptr;
std::string model;
public:
// Constructor - can start with no engine
SmartCar(const std::string& model)
: model(model) {
}
void setEngine(std::unique_ptr<Engine> newEngine) {
engine = std::move(newEngine);
}
void startCar() {
std::cout << model << " attempting to start..." << std::endl;
if (!engine) { // or: if (engine == nullptr)
std::cout << "ERROR: No engine installed!" << std::endl;
return;
}
engine->start();
std::cout << "Power: " << engine->getHorsepower() << " HP"
<< std::endl;
}
};
int main() {
std::cout << "===== RAW POINTER EXAMPLE =====" << std::endl;
// Start with no engine
Car car1("Honda Civic");
car1.startCar();
std::cout << "\n--- Installing engine ---\n" << std::endl;
Engine* v6 = new V6Engine();
car1.setEngine(v6);
car1.startCar();
delete v6;
std::cout << "\n\n===== SMART POINTER EXAMPLE =====" << std::endl;
// Start with no engine (nullptr or omit the parameter)
SmartCar car2("Tesla Model S"); // No engine parameter
car2.startCar();
std::cout << "\n--- Installing engine ---\n" << std::endl;
car2.setEngine(std::make_unique<V8Engine>());
car2.startCar();
std::cout << "\n--- Removing engine ---\n" << std::endl;
car2.setEngine(nullptr);
car2.startCar();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment