Main Menu


Sponsored Links

  


  
  
Web Cartoon Maker: a Fun Way to Learn C++ Contents Previous Next

Call Pass by Reference

An alternative parameter-passing mechanism that is available in C++ is called “pass by reference.” This mechanism makes it possible to pass an object to a procedure and modify it.

For example, you can reflect a point around the 45-degree line by swapping the two coordinates. The most obvious (but incorrect) way to write a Reflect function is something like this:

void Reflect ( Point P ) // WRONG !!

{

double dTemp = P.dX;

P.dX = P.dY;

P.dY = dTemp;

}

But this won’t work, because the changes we make in reflect will have no effect on the caller.

Instead, we have to specify that we want to pass the parameter by reference. We do that by adding the ampersand (&) operator to the parameter declaration:

void Reflect ( Point &P )

{

double dTemp = P.dX;

P.dX = P.dY;

P.dY = dTemp;

}

Now we can call the function in the usual way:

Max.SetPos ( MyPoint.dX, MyPoint.dY );

Reflect ( MyPoint );

Max.GoesTo ( MyPoint.dX, MyPoint.dY, 5 );

Here’s how we would draw a stack diagram for this program:

The parameter P is a reference to the object named MyPoint . The usual representation for a reference is a dot with an arrow that points to whatever the reference refers to.

The important thing to see in this diagram is that , unlike the “pass by value example,” any changes that Reflect makes in P will also affect MyPoint .

Passing objects by reference is more versatile than passing by value, because the callee can modify the object. It is also faster, because the system does not have to copy the whole object. On the other hand, it is less safe, since it is harder to keep track of what gets modified where.

Nevertheless, in C++ programs, almost all objects are passed by reference almost all the time. In this book I will follow that convention since the chances for confusion in WCM are minimal compared to the advantages of this approach – but beware that this is not always the case. It is especially very convenient and safe to pass internal WCM objects (Image, Text and characters) by reference.


Contents Previous Next
  
News

New Tales Animator Video by Alan Sturgess

Alan Sturgess shared an excellent video he made using Tales Animator! You can still download Tales Animator here. Unfortunately it is only available for Wi

...

Simple Online Character Designer

There is a prototype of simple online character designer available HERE. It is only a prototype, it does not contain many pieces yet but it can already generat

...

Book is updated

Now our book "Web Cartoon Maker: A Fun Way to Learn C++" is fully in synch with WCM 1.5! It is available for download and online reading HERE.

...

Web Cartoon Maker 1.5 is here!

Web Cartoon Maker 1.5 is finally here! You can download it HERE! Here is what was updated in version 1.5: Web Cartoon Maker Desktop Edition is now fully standal

...

read more news...


Poll