Why do I get an error while compiling this code that overloads the addition operator?
Feb 22, 2016 at 5:35am UTC
Hello everyone. I'm just going to get straight to the point. While compiling my c++ source code on overloading the addition operator I get an error called unhandled exception. I don't understand why. Here is the code I wrote.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
// Overloaded + operator
#include <iostream>
using namespace std;
class Box
{
private :
int area;
public :
// Constructor
Box(int a)
{
area = a;
}
// Accessor Function
void displayArea()
{
cout << area << endl;
}
// Friend of overloaded + operator function
friend Box operator +(const Box &lhs, const Box &rhs);
};
// Declare Overloaded + Operator Function
Box operator +(const Box &lhs, const Box &rhs)
{
Box sum = lhs;
sum = sum + rhs;
return sum;
}
// Main Function
int main()
{
// Create Box Objects
Box wood(10);
Box steel(20);
Box sum = wood + steel;
// Display the 2 objects data
cout << "Wood area: " ;
wood.displayArea();
cout << "Steel area: " ;
steel.displayArea();
// Display the sum of wood object and steel object
cout << "Sum of wood + steel: " ;
sum.displayArea();
char c;
cin >> c;
return 0;
}
Why does my code not work? Thank you.
Is there something wrong with my operator function? Thank you
Last edited on Feb 22, 2016 at 5:36am UTC
Feb 22, 2016 at 5:44am UTC
Line 36 sum = sum + rhs;
is recursively invoking the + operator over and over again until the program runs out of stack space.
Feb 22, 2016 at 9:00am UTC
Im assuming you want to add the area's of the two objects. In that case, you'll need to use the dot operator to access the area member variable. Once you've added area of lhs and area of rhs, simply return the sum object.
Topic archived. No new replies allowed.