Dependency Injection in C++
c++, dependency-injection, refactoring
Solution
Just use a shared_ptr to the service you need, and make a setter to it. E.g.:
class Engine;
class Car {
public:
void setEngine(shared_ptr<Engine> p_engine) {
this->m_engine = p_engine;
}
int onAcceleratorPedalStep(int p_gas_pedal_pressure) {
this->m_engine->setFuelValveIntake(p_gas_pedal_pressure);
int torque = this->m_engine->getTorque();
int speed = ... //math to get the car speed from the engine torque
return speed;
}
protected:
shared_ptr<Engine> m_engine;
}
// (now must create an engine and use setEngine when constructing a Car on a factory)
Avoid using auto_ptr, because you can't share it through more than one object (it transfers ownership when assigning).
Problem
How do I implement dependancy injection in C++ explicitly without using frameworks or reflection? I could use a factory to return a auto_ptr or a shared_ptr. Is this a good way to do it?