Passing References to Objects Assignment Help

Assignment Help: >> Data Types, Variables and Operators in C++ - Passing References to Objects

Passing References to Objects

No copy of the object is made when you pass by reference. Which means that no object used as a parameter is destroyed when the function terminates and the parameter's destructor is not called. For instance, try this program:

#include<iostream.h>

class c1

{

int id; public: int i; c1(int i);

~c1();

void neg(c1 &o){0.i=-0.i;}

};

c1::c1(int num)

{

cout <<"Constructing"<<num<<"\n";

id=num;

}

c1::~c1()

{

cout <<"Destructing "<<id<<"\n";

}

main()

{

c1 o(1); o.i=10; o.neg(o);

cout <<o.i<<"\n";

return 0;

}

here is the output of the program:

Constructing 1

-10 destructing 1

as we can see, only one call is made to c1's destructor function. Had o been passed through value, a second object would have been created inside the neg() and the destructor would have been called a second time when that object was destroyed at the time neg() terminated.

When we passing the parameters by reference, note that modifications to the object within the function affect the calling object.

Free Assignment Quote

Assured A++ Grade

Get guaranteed satisfaction & time on delivery in every assignment order you paid with us! We ensure premium quality solution document along with free turntin report!

All rights reserved! Copyrights ©2019-2020 ExpertsMind IT Educational Pvt Ltd