Section 4 - Returning Objects
7A.4.1 Assignments with Objects
When we make an assignment between two ints:
int x = 19, y; y = x;
There is little doubt what gets assigned. The value stored in x is copied into the variable location y. After this assignment statement, x and y can have separate and independent futures What happens to one will not affect the other. This is true because they are both primitive data types.
With objects of classes, the same is true. Lets say r1 and r2 are Rectangle objects. (Since shortly, I'm going to add a label member to the Rectangle class, the code below will anticipate this addition.) Consider the following:
// create a new rectangle, r1, with dimensions 5 x 8 Rectangle r1; r1.label = 'a'; r1.setWidthHeight(5, 8); // create a new rectangle, r2, with dimensions 2 x 2 Rectangle r2; r2.label = 'b'; r2.setWidthHeight(2, 2); // now assign r1 to r2: r2 = r1;
What just happened? We instantiated two separate objects that were named r1 and r2, but then along came the assignment statement r2 = r1. As with the ints the value of r1 is copied into r2. However, since there are several members that comprise a Rectangle (as opposed to only one number that is stored in an int), this assignment actually moves all the data from r1 into r2, so it is a more substantial assignment. It is equivalent to this more verbose code:
r2.width = r1.width; r2.height = r1.height; r2.label = r1.label;
Of course, if the data were private, we could not even do the latter sequence; we would need accessor methods:
r2.setWidth( r1.getWidth() ); r2.setHeight( r1.getHeight() ); r2.setLabel( r1.getLabel() );
The assignment r2 = r1 is a little different from that of other languages, so if you come from Java, C# or Visual Basic, you will want to make a note of this. r1 and r2 are objects, not references (to use other languages' terminology).
7A.4.2 Functions that Return Objects
This same sort of analysis applies to methods that have return types that are class names, as in:
Rectangle Rectangle::whichIsBigger(Rectangle r1, Rectangle r2) { // definition omitted for now - returns Rectangle with larger area }
As you see, we are going to return the larger Rectangle. But what, exactly are we returning, and how would we capture the result in the client?
The answer is, we are returning an object, and we would capture it usually with an assignment statement. And now that we know an assignment statement copies all the data from one object to another, this means that all the data inside the object is being returned.
r3 = Rectangle::whichIsBigger(r1, r2);
Okay, we're ready to see the entire Rectangle example. We don't even have to discuss it because we have already done so!