-3

When a class object is passed by value to any function, the copy constructor is called to create a local object and the destructor is called when the object is returned. But, will copy constructor be called if the object reference is passed?

Davide Spataro
  • 7,319
  • 1
  • 24
  • 36
Reena Cyril
  • 417
  • 4
  • 11

1 Answers1

2

Nope, it won't be called.

A reference is an alias, that is, another name for an already existing variable and not for a copy.

Take a look at this example:

class Line {
public:
   int getLength( void ){}
   // simple constructor
   Line(  ){
      cout<<"constructor"<<endl;
   }   
   // copy constructor          
   Line( const Line &obj){
      cout<<"copy cts\n";
   }  
};

void callR(Line& l){
   cout<<"call by ref\n";
}
void callC(Line l){
   cout<<"call by copy\n";
}


int main() {

   Line line;
   cout<<"before call by reference\n";
   callR(line);
   cout<<"before call by copy\n";
   callC(line);
}

which produces the following output:

constructor ->  Line line;
before call by reference
call by ref 
before call by copy
copy cts
call by copy

As you can see copy constructor is not called when an object is passed by reference. Think of a reference as a pointer.

Davide Spataro
  • 7,319
  • 1
  • 24
  • 36