Dependency Injection

How Does Dependency Injection Work Internally?

In plain C++, dependency injection works through normal code, with no hidden engine. Learn how object creation, ownership and virtual calls work together.

On this page
  1. What happens when the object is created
  2. How a call reaches the implementation
  3. Ownership decides who cleans up
  4. What libraries add
  5. Common pitfalls

How does dependency injection work internally? In plain C++, the answer is ordinary code. An object receives a pointer or reference to its dependency, stores it, and later calls a virtual function on it. No hidden engine runs in the background. Some libraries add automation on top, which is covered near the end of this article.

What happens when the object is created

The following sequence shows the steps. It assumes UserService takes a std::unique_ptr<Logger> in its constructor and stores it in a member.

auto logger = std::make_unique<ConsoleLogger>();  // 1. Create the implementation
UserService service(std::move(logger));          // 2. Hand ownership to the service
service.create_user("Ada");                      // 3. The call goes through the Logger interface

In step 1, the ConsoleLogger is created on the heap, and logger holds the only pointer to it. In step 2, ownership moves into service. After the move, logger no longer owns anything, and no copy of the logger is made. In step 3, UserService calls log through its Logger pointer, and the call reaches ConsoleLogger.

How a call reaches the implementation

Inside UserService, the call logger_->log(...) is resolved at run time, because log is a virtual function. Most mainstream C++ compilers implement this with a virtual table, or vtable: a table of function addresses that each class with virtual functions has. Every object of such a class carries a hidden pointer to its table. The call looks up log in that table and jumps to the version for the object’s real type.

The C++ standard does not require this design, but most compilers use it. The cost is one extra indirect jump per call. For most programs it is small. In very hot loops it can matter, and compilers sometimes remove the indirection when they can see the concrete type. If speed is a concern, measure first.

Ownership decides who cleans up

  • std::unique_ptr has one owner. The dependency is destroyed when that owner is destroyed.
  • std::shared_ptr has shared ownership. The dependency is destroyed when the last owner goes away, at the cost of maintaining a reference count.
  • A reference or raw pointer has no ownership. The caller must make sure the dependency lives as long as the class uses it.

What libraries add

Standard C++ has no run-time reflection, so a library cannot ask a class at run time which constructor parameters it has. Container libraries work around this in different ways. Some use templates to work out the parameter types at compile time. Others ask you to register a factory function for each type. Either way, the job is the same: build the objects in the right order and pass in their dependencies. When that work is automated, the tool that does it is usually called a dependency injection container.

Common pitfalls

  • Dangling references. A class that stores a Logger& to an object that has been destroyed is left with a dangling reference. Using it is undefined behavior.
  • Calling a setter too late. If a class uses a dependency before a setter provides it, the pointer is still null.
  • Circular dependencies. If A needs B and B needs A, constructor injection cannot build either one first. Break the loop, for example by having one class take a setter.

The complete guide to dependency injection

Dependency Injection in C++
Read the guide

Keep exploring

Guides from other topics

All topics →

std::list in C++

std::list is the C++ standard library's doubly linked list. Learn to create one, add and remove elements, loop through it, and when to pick it over a vector.

std::list 5 min read