The book I'm using continues to give me code and fails to explain the syntax. I got to a chapter on operator overloading and it gave me some code but didn't actually explain any of the code. I having trouble understanding the Rectangle operator+ line and that methods contents. Why does there need to be a constant? why is there an & symbol at the end of Rectangle in the argument list? What is the difference between width and p1.width? Thanks

#include <iostream>
using namespace std;

class Rectangle
{
    public:
        Rectangle()
        {
            width = 0;
            height = 0;
        }

        Rectangle(int nx, int ny)
        {
            width = nx;
            height = ny;
        }

        ~Rectangle() {}

        Rectangle operator+ (const Rectangle& p1)
        {
            return Rectangle(width + p1.width, height + p1.height);
        }

        int getWidth() { return width; }
        int getHeight() { return height; }

    private:
        int width; // width of our rectangle
        int height; // height of your rectangle
};

int main()
{
    Rectangle ptA(1, 2);        // create a 1x2 rec
    Rectangle ptB(3, 4);        // create a 3,4 rec
    Rectangle ptC = ptA + ptB;  // add them together

    cout << "THe sum of RectangleA and RectangleB is:= (" << ptC.getWidth() << "," << ptC.getHeight() << ")" << endl;

    return 0;
}
Rectangle operator+ (const Rectangle& p1)
{
    return Rectangle(width + p1.width, height + p1.height);
}

Breaking down this function we see the return type is a Rectangle. In the parameter list we have const Rectangle& which means give me a constant Rectangle reference. & means reference and a reference is basically a pointer but you use it like a regular variable. passing a reference of an object to functions is cheaper then passing the function by value so that is why it is done. const is in there so that you can pass a constant or non constant variable. if const wasn't there you would not be able to pass constant variables to the function.

In the function width is the width of the object that is having plus called on where as p1.width is the with of the rectangle that was passed to +.

Comments
Good explanation
This article has been dead for over six months. Start a new discussion instead.