I'm new to C++, with a C# background. I'm trying to use dependency injection commonly used in C# in C++ and I'm confused about the different ways to declare dependencies and pass them in and why I would use one over the other. Let's assume A depends on B.
Approach #1 - declare as object and take object
class A
{
  private:
    B _b;
  public:
    A(B b): _b(b) { }
    void Foo()
    {
        _b.Bar();
    }
}
Approach #2 - declare as object and take reference
class A
{
  private:
    B _b;
  public:
    A(B &b): _b(b) { }
    void Foo()
    {
        _b.Bar();
    }
}
Approach #3 - declare as reference and take object - scratch this - undefined behavior
class A
{
  private:
    B &_b;
  public:
    A(B b): _b(b) { }
    void Foo()
    {
        _b.Bar();
    }
}
Approach #4 - declare as reference and take reference
class A
{
  private:
    B &_b;
  public:
    A(B &b): _b(b) { }
    void Foo()
    {
        _b.Bar();
    }
}
I've tried all of the above and they all seem to work. Is there any difference between them? and if so why should I choose one over the other? my preference is #1 because I find it the most familiar and intuitive.
I've found a similar discussion discussion here but that's more about Pointers vs References.
 
     
    