简体   繁体   中英

confusion in constructor calling in virtual function

Confusion in constructor calling via temporary object as argument in a function

#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;
}

My question is that why there is no call to Default Constructor of Base Class,when we are creating a Temporary object of a Base class in function ( void somefunc(Base obj) )

My question is that why there is no call to Default Constructor of Base Class,when we are creating a Temporary object of a Base class in function

An instance of Base is constructed using the copy constructor when the call to somefunc is made. That object is not constructed using the default constructor. A default copy constructor is created by the compiler since you haven't defined one.

It's not a temporary object. The argument is passed by value to the function, so the copy ctor will be called, not default ctor. Note that compiler will provide a copy constructor if there is no user defined, you can define it by yourself to output some debug info.

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

它将调用copy construct函数在函数中创建Base类的Temporary对象

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM