在虚函数中调用构造函数时出现混淆

confusion in constructor calling in virtual function

本文关键字:构造函数 函数 调用      更新时间:2023-10-16

通过临时对象作为函数参数调用构造函数时的混淆

#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 Basen";
      }
};
class Derived : public Base
{
   int j;
   public:
   Derived(int a, int b) : Base(a) { 
      j = b; 
      cout<<"Derived constructorn"; 
   }
   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))中创建基类的临时对象

我的问题是,当我们在函数

中创建基类的临时对象时,为什么没有调用基类的默认构造函数?

在调用somefunc时,使用复制构造函数构造Base的实例。该对象不是使用默认构造函数构造的。由于没有定义默认复制构造函数,因此编译器会创建默认复制构造函数。

这不是一个临时对象。参数按值传递给函数,因此将调用复制函数,而不是默认函数。注意,如果没有用户自定义,编译器会提供一个复制构造函数,你可以自己定义它来输出一些调试信息。

Base(const Base& a) : i (a.i) 
{
    cout<<"Base copy constructor n"; 
}

它将调用copy construct函数在函数

中创建基类的临时对象