order of calling constructor in inheritance

你离开我真会死。 提交于 2021-02-05 08:46:34

问题


I am new to C++ programming language, i have a confusion about order of calling the constructor in inheritance. my question is even though the constructor and destructor are not inherited by derived class why the base class constructor will call when i create a derived class object.


回答1:


The purpose of a constructor is to define how the data members should be initialised. Since a derived class inherits the data members from the base class, any constructor of the derived class must define not only how to initialise the data members that are specific to the derived class, but also those coming from the base class.

The natural way to do this (and required by the C++ Standard) is by calling a base class constructor. If you don't include a specific constructor call in the initialization list for your derived-class constructor, the default constructor of the base class will be used to initialise the base-class members.

struct base
{
   int _i;               // a data member
   base():_i(0) {}       // default constructor
   base(int i):_i(i) {}  // special constructor
};

struct derived : base
{
  int _j;                         // a data member specific to the derived class
  derived(int i, int j):_j(j) {}  // user-defined constructor for the derived class
};

The example above illustrates how the derived-class constructor can initialise its member _j, but the member _i, coming from the base class, must be initialised using a base-class constructor.

The way it's written above, the default constructor base::base() will be automatically called by the compiler, i.e. _i will be initialised to 0.

But you can change that behaviour by including a call to a specific constructor:

struct derived : base
{
  int _j;
  derived(int i, int j):base(i),_j(j) {}  // user-defined constructor for the derived class
};

The order of the constructor calls is: First constructor calls of the base class, then initializers for the derived-class specific members. This is only natural because the derived class, in a sense, is an extension of the base class, and it makes sense to regard the base-class part of the derived-class object as being there first.



来源:https://stackoverflow.com/questions/14868971/order-of-calling-constructor-in-inheritance

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!