Operator overloading issue

0 Alex Dale · June 22, 2015
been trying to figure out operator overloading for the last week, what is wrong with the code I have here? also why must you declare the class const and why must you use the adress of the object in the operator parameters?

#include <iostream>

using namespace std;

class Comparison

    Comparison(int x)
        x = num;
    friend Comparison operator+(const Comparison &otherObject,const Comparison &otherObject2);

    int num;

Comparison operator+(const Comparison &otherObject,const Comparison &otherObject2)
        cout << otherObject.num + otherObject2.num;
        return otherObject.num + otherObject2.num;

int main()
    Comparison a(5);
    Comparison b(9);
    Comparison c;

    c = a+b;

    return 0;

Post a Reply


Oldest  Newest  Rating
0 Alper Akgoz · June 23, 2015
You made a simple mistake in one of the constructors. You have x = num, when you are suppose to have num = x. You must declare it constant because values of left and right should not change after doing the operation, since you are getting a new result. If you want the operands to change then you have to use mutators. I'm not sure about why you need to pass by reference though.
  • 1



Used in many types of software including music players, video games, and many large scale applications.

Bucky Roberts Administrator