派生型の基本クラスのコンストラクターが呼び出されるのはなぜですか? 質問する

派生型の基本クラスのコンストラクターが呼び出されるのはなぜですか? 質問する
#include <iostream>
#include <stdio.h> 
using namespace std;

// Base class
class Shape 
{
   public:
      void setWidth(int w)
      {
         width = w;
      }
      void setHeight(int h)
      {
         height = h;
      }
      Shape()
      {
    printf("creating shape \n");
      }
      Shape(int h,int w)
      {
     height = h;
         width = w;
         printf("creatig shape with attributes\n");
      } 
   protected:
      int width;
      int height;
};

// Derived class
class Rectangle: public Shape
{
   public:
      int getArea()
      { 
         return (width * height); 
      }
      Rectangle()
      {
     printf("creating rectangle \n");
      }
      Rectangle(int h,int w)
      {
     printf("creating rectangle with attributes \n");
     height = h;
         width = w;
      }
};

int main(void)
{
   Rectangle Rect;

   Rect.setWidth(5);
   Rect.setHeight(7);

   Rectangle *square = new Rectangle(5,5);
   // Print the area of the object.
   cout << "Total area: " << Rect.getArea() << endl;

   return 0;
}

プログラムの出力は以下のとおりです。

creating shape 
creating rectangle 
creating shape 
creating rectangle with attributes 
Total area: 35

両方の派生クラス オブジェクトを構築するときに、最初に呼び出されるのは常に基本クラスのデフォルト コンストラクターであることがわかります。これには理由がありますか? Python などの言語が、C++ のような暗黙的な呼び出しではなく、基本クラス コンストラクターの明示的な呼び出しを要求するのは、このためですか?

ベストアンサー1

これに対する簡単な答えは、「それが C++ 標準で指定されているから」です。

次のように、デフォルトとは異なるコンストラクターをいつでも指定できることに注意してください。

class Shape  {

  Shape()  {...} //default constructor
  Shape(int h, int w) {....} //some custom constructor


};

class Rectangle : public Shape {
  Rectangle(int h, int w) : Shape(h, w) {...} //you can specify which base class constructor to call

}

呼び出すコンストラクターを指定しない場合にのみ、基本クラスのデフォルト コンストラクターが呼び出されます。

おすすめ記事