1

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) )

R Sahu
  • 204,454
  • 14
  • 159
  • 270
Nadeem Bhati
  • 739
  • 1
  • 8
  • 13

3 Answers3

4

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.

R Sahu
  • 204,454
  • 14
  • 159
  • 270
3

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"; 
}
songyuanyao
  • 169,198
  • 16
  • 310
  • 405
1

it will call copy construct function to create the Temporary object of a Base class in function

kiviak
  • 1,083
  • 9
  • 10