In this specific case, is there a difference between using a member initializer list and assigning values in a constructor?

后端 未结 12 901
北恋
北恋 2020-11-22 08:16

Internally and about the generated code, is there a really difference between :

MyClass::MyClass(): _capacity(15), _data(NULL), _len(0)
{
}

12条回答
  •  太阳男子
    2020-11-22 08:53

    Here is a point that I did not see others refer to it:

    class temp{
    public:
       temp(int var);
    };
    

    The temp class does not have a default ctor. When we use it in another class as follow:

    class mainClass{
    public:
     mainClass(){}
    private:
      int a;
      temp obj;
    };
    

    the code will not compile, cause the compiler does not know how to initialize obj, cause it has just an explicit ctor which receives an int value, so we have to change the ctor as follow:

    mainClass(int sth):obj(sth){}
    

    So, it is not just about const and references!

提交回复
热议问题