-1

I've written a little sample code below.

#include <iostream>
#include <cstdio>

using namespace std;   
class Box{
    int l; //length
    int b; //breadth
    int h; //height
public:
    Box(){ l =0; b = 0; h = 0;}
    Box(int d1, int d2, int d3){ l = d1;b=d2;h=d3;}
    int getLength(){return l;}
    friend Box operator+(Box b1, Box b2){
        Box tempBox;
        tempBox.l = b1.l + b2.l;
        tempBox.b = b1.b + b2.b;
        tempBox.h = b1.h + b2.h;
        return tempBox;
    }
    int calculateVolume(){ return l * b * h;}
}; 

This code doesn't produce errors when compiled/run. We can also change the friend function to the following:

friend Box operator+(Box &b1, Box &b2){
    Box tempBox;
    tempBox.l = b1.l + b2.l;
    tempBox.b = b1.b + b2.b;
    tempBox.h = b1.h + b2.h;
    return tempBox;

and the test code runs equally well. My question is, what is the purpose of referencing the Box objects 'b1' and 'b2' by their memory addresses like in the second version of the friend function, something I see often in sample code? More to the point, if we're passing addresses to the friend function, how does it know to manipulate the objects stored at those addresses without any sort of dereferencing? Sorry, I'm a bit new to all this. Any help would be appreciated!

Gimingo
  • 1
  • 1
  • 3
    You need to learn some C++ basics. The `&` means call by reference instead of call by value. – stark Jan 10 '17 at 00:08
  • Get a good book, read about c++ references. Your first example and second example, look similar but are doing wildly different things underneath. Read some pass by reference stuff. – Fantastic Mr Fox Jan 10 '17 at 00:08
  • @Ben: Not that "wild", really. In fact, it wouldn't surprise me if the generate assembly ended up being more or less the same, when all's said and done. Three unneeded integer copies are easy to elide. – Lightness Races in Orbit Jan 10 '17 at 00:18
  • @LightnessRacesinOrbit I meant more that, it can be. If box had a 100*100 array or something big that has a copy constructor, you end up doing something pretty different to just referencing an object. – Fantastic Mr Fox Jan 10 '17 at 01:12

1 Answers1

0

referencing the Box objects 'b1' and 'b2' by their memory addresses like in the second version

That is not what is happening. & in its "address-of operator" guise is not being used here.

Though technically the difference lies in context rather than in whitespace placement, we can more clearly write the code as follows:

friend Box operator+(Box& b1, Box& b2){

Box& is the type "reference to Box".

References prevent unnecessary copying. Read the chapter in your book about references for more information.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055