How to create the object required for the class constructor when the control is inverted?

I program in C ++ using TDD, which suggests using control inversion when creating objects (when creating objects of a particular class, pass the objects built to it to the constructor). This is great, but how do I create the objects needed by the constructor?

I am currently using a factory (which I can easily modify for my unit tests), which returns shared_ptr pointing to the created object. Is this right, or are there any better ways to do this?

A very simplified example demonstrates what I'm doing:

#include <iostream>

struct A {
    virtual ~A() { }
    virtual void foo() = 0;
};

struct B : A {
    virtual ~B() { }
    virtual void foo() { std::cout<<"B::foo()"<<std::endl; }
};

struct C {
    C( A *a ) : a(a) { }
    void DoSomething() { a->foo(); }

    A *a;
};

int main() {
    C c( new B );

    c.DoSomething();
}

against it:

#include <iostream>

struct A {
    virtual ~A() { }
    virtual void foo() = 0;
};

struct B : A {
    virtual ~B() { }
    virtual void foo() { std::cout<<"B::foo()"<<std::endl; }
};

struct C {
    C() : a() { }
    void DoSomething() { a.foo(); }

    B a;
};

int main() {
    C c;   // the object of type B is constructed in the constructor

    c.DoSomething();
}

EDIT1

This link explains IoC for java, but as you know in java you can do something like this:

class B
{
};
class A
{
  public:
    A( B b )
...
};

...
A objA( new B );   // this doesn't work in c++
...
+3
1

Builder. Builder Factory - , , , Builder , , .

, . , .

(4 !), . .

, IOC, - . ( ) .

+2

Source: https://habr.com/ru/post/1774071/


All Articles