How to properly initialize a non-standard element of a class?

Suppose I define a class Foothat does not implement the default constructor. In addition, I have a class Barthat owns an instance Foo:

class Foo() {
  private:
    int m_member;
  public:
    Foo( int value ) : m_member(value) { }
};

class Bar() {
  private:
    Foo m_foo;
  public:
    Bar( /* ... */ ) {
      int something;
      /* lots of code to determine 'something' */
      /* should initialize m_foo to 'Foo(something)' here */
    }
};

The code, as shown, will not work because it is Bartrying to call the default constructor Foo.

Now I'm trying to make the constructor Barfirst define something, and then pass the result to the constructor Foo.

- Bar / Foo m_something. , , m_foo -.

Foo , , Foo ( ).

? /?

+4
2

, -, m_foo .

class Bar {
  private:
    Foo m_foo;
  public:
    Bar( /* ... */ ) : m_foo(calculate_something()) {
    }
private:
    static int calculate_something()
    {
       int something = 0;
       // lot of code to calculate something
       return something;
    }
};
+12

Bar? , , . -

class Bar {
  public:
    Bar(int param, Foo foo): m_foo(foo) {
        // do just some very simple calculations, or use only constructor initialization list
    }
  ...
}

class BarBuilder {
  public:
    BarBuilder(/*...*/) {
        // do all calculations, boiling down to a few parameters for Bar and Foo
       Foo foo(fooParameter);
       m_result = new Bar(barParameter, foo); // give Foo here explicitly
    }
    Bar getResult() { return *m_result; }
  private:
    Bar* m_result; // or better use unique_ptr  
}

Builder, , , .

, , , , .

+2

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


All Articles