Alonso
Alonso

Reputation: 35

Why is my overloaded "+" operator returning the wrong total amount?

So i'm trying to wrap my head around operator overloading and I'm trying to add the lengths and heights of two instantiated boxes in main(). Problem is that the total should be myBox(2,4) + myBox2(1,2) = (3,6), yet the output total incorrectly displays "2 / 3".

#include<iostream>

using namespace std;

class Box {

    public:
        int length, height;
        Box(){ 
            length = 1, height = 1;
        }
        Box(int l , int h) {
            length = l, height = h;
        }
        Box operator +(const Box& boxToAdd) {
            Box boxSum;
            boxSum.length = boxSum.length + boxToAdd.length;
            boxSum.height = boxSum.height + boxToAdd.height;
            return boxSum;
        }
    };


    ostream& operator<<(ostream& os, const Box& box) {
    os << box.length << " / " << box.height << endl;
        return os;

    }
    int main() {
        Box myBox(2,4);
        cout << "First box length and height: "<<myBox << endl; // Outputs length and height data member values.
        Box myBox2(1, 2);
        cout << "Second box length and height: " << myBox2 << endl;

        cout << "The total of both boxes is: " << myBox + myBox2 << endl;
        cin.get();
}

Upvotes: 0

Views: 56

Answers (1)

songyuanyao
songyuanyao

Reputation: 172994

In operator+, you're perform addition from boxSum; which is defalut-constructed just now with length = 1, height = 1;, then you got the result 2 (1 + 1) and 3 (2 + 1). You should perform addition from the current instance. e.g.

Box operator +(const Box& boxToAdd) {
    Box boxSum;
    boxSum.length = this->length + boxToAdd.length;
    boxSum.height = this->height + boxToAdd.height;
    return boxSum;
}

LIVE

Upvotes: 2

Related Questions