1

関数の引数として一時オブジェクトを介してコンストラクターを呼び出す際の混乱

#include <iostream>
using namespace std;

class Base
{
   protected:

      int i;

   public:

      Base() {
         cout<<"\n Default constructor of Base \n";
      }

      Base(int a)
      {
         i = a;        
         cout<<"Base constructor \n"; 
      }

      void display(){ 
         cout << "\nI am Base class object, i = " << i ;
      }

      ~Base(){
         cout<<"\nDestructor of Base\n";
      }
};

class Derived : public Base
{
   int j;

   public:

   Derived(int a, int b) : Base(a) { 
      j = b; 
      cout<<"Derived constructor\n"; 
   }

   void display()   { 
      cout << "\nI am Derived class object, i = "<< i << ", j = " << j; 
   }

   ~Derived(){
      cout<<"\nDestructor Of Derived \n";
   }
};


void somefunc (Base obj)    //Why there is no call to default constructor of Base class 
{
   obj.display();
}


int main()
{

   Base b(33);

   Derived d(45, 54);

   somefunc( b) ;

   somefunc(d); // Object Slicing, the member j of d is sliced off

   return 0;
}

私の質問は、関数 ( void somefunc(Base obj) ) で基本クラスの一時オブジェクトを作成しているときに、基本クラスの既定のコンストラクターへの呼び出しがない理由です。

4

3 に答える 3