12.12.2012 Views

Teach Yourself Borland C++ in 14 Days - portal

Teach Yourself Borland C++ in 14 Days - portal

Teach Yourself Borland C++ in 14 Days - portal

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

80 Day 3<br />

TIP<br />

Remember that a function can return only one value. By pass<strong>in</strong>g<br />

parameters by reference you can achieve the effect of a function<br />

return<strong>in</strong>g more than one value. The function still only returns one<br />

value, but the objects passed by reference are updated, so the function<br />

effectively returns multiple values.<br />

As I said, the other reason to pass parameters by reference is to elim<strong>in</strong>ate the overhead of<br />

mak<strong>in</strong>g a copy of the object each time the function is called. When deal<strong>in</strong>g with primitive<br />

data types, there is no real overhead <strong>in</strong>volved <strong>in</strong> mak<strong>in</strong>g a copy. When deal<strong>in</strong>g with structures<br />

and classes, however, the overhead is someth<strong>in</strong>g to be considered. You should pass structures<br />

of any consequence by reference, as the follow<strong>in</strong>g code demonstrates:<br />

// structure passed by reference<br />

void someFunction(MyStructure& s)<br />

{<br />

// do some stuff with ‘s’<br />

return;<br />

}<br />

MyStructure myStruct;<br />

// do some stuff, then later...<br />

someFunction(myStruct);<br />

Notice that the function call looks exactly the same whether the object is be<strong>in</strong>g passed by<br />

reference or by value.<br />

Do you see a potential problem with pass<strong>in</strong>g by reference? If you pass by reference, you avoid<br />

the overhead of mak<strong>in</strong>g a copy of the object, but now the object can be modified by the<br />

function. Sometimes you don’t want the object to be modified by the function. So what if you<br />

want to pass by reference but make sure the object is not modified? Read on and I’ll tell you.<br />

The const Keyword<br />

NEW TERM<br />

The const keyword will allow you to declare a variable as constant.<br />

Once a variable is declared with const, it cannot be changed. The solution, then, is to pass<br />

by reference and make the object const:<br />

void someFunction(const MyStruct& s)<br />

{<br />

// do some stuff with ‘s’<br />

return;<br />

}<br />

MyStructure myStruct;<br />

// later<br />

someFunction(myStruct);

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!