c++ - Is the copy constructor called when an object is passed by reference? -


when class object passed value function, copy constructor called create local object , destructor called when object returned. but, copy constructor called if object reference passed?

nope, won't called.

a reference alias, is, name an existing variable , not copy.

take @ 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 ref\n"; } void callc(line l){    cout<<"call copy\n"; }   int main() {     line line;    cout<<"before call reference\n";    callr(line);    cout<<"before call copy\n";    callc(line); } 

which produces following output:

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

as can see copy constructor not called when object passed reference. think of reference pointer.


Comments

Popular posts from this blog

php - Vagrant up error - Uncaught Reflection Exception: Class DOMDocument does not exist -

vue.js - Create hooks for automated testing -

Add new key value to json node in java -