What is dependency injection in C++? It is a design technique where a class gets the objects it depends on from outside, instead of creating them itself. In C++, this usually means passing those objects in through the constructor. The class stays focused on its own job, while the code that creates it decides which implementation it uses.
A simple example
Imagine a Car that needs an engine. Without injection, the car would create its own engine, which locks it to one type. With injection, the car asks for an Engine and uses whichever one it receives:
#include <iostream>
#include <memory>
#include <utility>
class Engine {
public:
virtual ~Engine() = default;
virtual void start() = 0;
};
class ElectricEngine : public Engine {
public:
void start() override {
std::cout << "Electric motor starting\n";
}
};
class Car {
public:
explicit Car(std::unique_ptr<Engine> engine)
: engine_(std::move(engine)) {}
void drive() {
engine_->start();
}
private:
std::unique_ptr<Engine> engine_;
};
int main() {
Car car(std::make_unique<ElectricEngine>());
car.drive(); // prints: Electric motor starting
}
Car knows only that it has an Engine. It does not know whether that engine is electric, gasoline, or a stand-in used in tests. The choice is made in main, where the car is created.
Why developers use it
- Flexibility. You can swap one implementation for another, such as a real database for an in-memory one, without editing the classes that use it.
- Testing. A test can pass in a fake dependency, so the code runs without a real database, network connection, or console.
- Clear requirements. The constructor lists what a class needs, so a reader can see its dependencies at a glance.
What dependency injection is not
Dependency injection is a way of organizing code, not a library you must install. Plain C++ is enough for the basic technique.
It is also not the same as a dependency injection container. A container is a tool that automates the wiring of objects. You can use DI without one, and small programs often do.
Dependency injection is not always worth the extra effort. A simple helper that will never change may be clearer as a plain function. Use injection where swapping or testing matters.
Key points
- A class receives its dependencies from outside.
- The constructor is the most common way to pass them in.
- Depend on an interface so the implementation can change.
- DI is a pattern you apply in ordinary code, not a special C++ feature.