What is the member variables list after the colon in a constructor good for?

前端 未结 8 1072
予麋鹿
予麋鹿 2020-12-11 02:34

I\'m reading this C++ open source code and I came to a constructor but I don\'t get it ( basically because I don\'t know C++ :P )

I understand C and Java very well.

8条回答
  •  盖世英雄少女心
    2020-12-11 03:01

    There are usually some good reasons to use an initialization list. For one, you cannot set member variables that are references outside of the initialization list of the constructor. Also if a member variable needs certain arguments to its own constructor, you have to pass them in here. Compare this:

    class A
    {
    public:
      A();
    private:
      B _b;
      C& _c;
    };
    
    A::A( C& someC )
    {
      _c = someC; // this is illegal and won't compile. _c has to be initialized before we get inside the braces
      _b = B(NULL, 5, "hello"); // this is not illegal, but B might not have a default constructor or could have a very 
                                // expensive construction that shouldn't be done more than once
    }
    

    to this version:

    A::A( C& someC )
    : _b(NULL, 5, "hello") // ok, initializing _b by passing these arguments to its constructor
    , _c( someC ) // this reference to some instance of C is correctly initialized now
    {}
    

提交回复
热议问题