C++ calling base class constructors

后端 未结 6 1888
无人及你
无人及你 2020-12-08 00:23
#include 
#include  
using namespace std;

// Base class
class Shape 
{
   public:
      void setWidth(int w)
      {
         width =         


        
6条回答
  •  抹茶落季
    2020-12-08 01:02

    In c++, compiler always ensure that functions in object hierarchy are called successfully. These functions are constructors and destructors and object hierarchy means inheritance tree.

    According to this rule we can guess compiler will call constructors and destructors for each object in inheritance hierarchy even if we don't implement it. To perform this operation compiler will synthesize the undefined constructors and destructors for us and we name them as a default constructors and destructors.Then, compiler will call default constructor of base class and then calls constructor of derived class.

    In your case you don't call base class constructor but compiler does that for you by calling default constructor of base class because if compiler didn't do it your derived class which is Rectangle in your example will not be complete and it might cause disaster because maybe you will use some member function of base class in your derived class. So for the sake of safety compiler always need all constructor calls.

提交回复
热议问题