Operator overloading question
Dec 3, 2011 at 2:40pm UTC
I had a question about the output of this code..
Shouldn't the output be both $1050. Instead of 1st output $1300 and 2nd output $650.. Or my logic is wrong in any way? I thought it overload the "+" so they will be able to 'recognise' what to add together if we do "clerk + driver"
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
#include <iostream>
using namespace std;
class Employee
{
private :
int idNum;
double salary;
public :
Employee(int , double );
double addTwo(Employee);
double operator +(Employee);
};
Employee::Employee(int num, double sal)
{
idNum= num;
salary = sal;
}
double Employee::operator +(Employee emp)
{
double total;
total = total + emp.salary;
return total;
}
int main()
{
Employee clerk(1234, 400.00);
Employee driver(3456, 650.00);
double sum;
sum = clerk.operator +(driver);
cout<<"Using operator+() function = Sum is $" <<sum<<endl;
sum = clerk + driver;
cout<<"Using + operator = Sum is $" <<sum<<endl;
}
Dec 3, 2011 at 2:54pm UTC
Notice how your operator + does not involve this->salary at all. total is garbage. Fix the operator and you'll be fine.
Dec 3, 2011 at 2:56pm UTC
sorry i dun get what u mean, can elaborate on it..?
Dec 3, 2011 at 2:57pm UTC
you didn't initialize your total with 0, so your total contains garbage !!
and also instead of your code, you can write
double Employee::operator+(Employee emp)
{
return salary + emp.salary ;
}
Topic archived. No new replies allowed.