Avoid calling constructor of member variable

后端 未结 9 1593
礼貌的吻别
礼貌的吻别 2021-02-19 13:14

I have the following C++-class:

// Header-File
class A
{
    public:
    A();

    private:
    B m_B;
    C m_C;
};

// cpp-File
A::A()
: m_B(1)
{
    m_B.doSom         


        
9条回答
  •  独厮守ぢ
    2021-02-19 14:07

    Here we have the building blocks:

    #include 
    
    class C
    {
    public:
      C(int i){std::cout << "C::C(" << i << ")" << std::endl;}
    };
    
    class B
    {
    public:
      B(int i){std::cout << "B::B(" << i << ")" << std::endl;}
      void doSomething(){std::cout << "B::doSomething()" << std::endl;}
      void doMore(){std::cout << "B::doMore()" << std::endl;}
      int getSomeValue(){return 42;}
    };
    

    If you want to make a new kind of construction for B consider making a derived class:

    class B1 : public B
    {
    public:
      B1() : B(1)
      {
        doSomething();
        doMore();
      }
    };
    

    Now use the class B1 that is derived from B:

    class A
    {
    private:
      B1 _b;
      C _c;
    public:
      A() : _c(_b.getSomeValue()){std::cout << "A::A()" << std::endl;}
    };
    

    And then:

    int main()
    {
      A a;
    }
    

    Output:

    B::B(1)
    B::doSomething()
    B::doMore()
    C::C(42)
    A::A()
    

提交回复
热议问题