I have a class employee
#include <iostream>
#include <string>
using namespace std;
class employee
{
public:
double operator + (employee);
employee(int);
double getSalary();
private:
double salary;
};
int main()
{
employee A(400);
employee B(800);
cout<<A+B;
employee C = A+B;
cout<<C.getSalary();
}
employee::employee(int salary)
{
this->salary = salary;
}
double employee::operator + (employee e)
{
double total;
total = e.salary + this->salary;
return total;
}
double employee::getSalary()
{
return this->salary;
}
I have overloaded the operator + so that it adds up the salary of 2 employee objects . The return type of the overloaded + operator is double.
This is my question
1) Why does employee C = A + B
work when i have overloaded the operator + to return a double and not a employee , shouldnt there be a compiler error??
2) what is actually happening???
When you overload operator+
to return a double, the compiler will look at whether it can convert that double
to an employee
object. Since you have a ctor that takes an int
, it does an implicit conversion from double
to int
, then uses your ctor to convert from int
to employee
.
So no, that shouldn't generate a compiler error.
At the same time, it doesn't make much sense. Right now, you've defined the employee
's salary member as a double
, but only allowed the user to specify an int
to initialize it. You probably want to allow initializing it with a double
instead.
As it stands right now, your operator+
also has asymmetric behavior: it can do implicit conversions on the right operand, but not on the left, so a + 1
works, but 1 + a
doesn't.
You can eliminate all implicit conversions by making your conversion constructors (i.e., all that can be invoked with a single parameter) explicit
. Conversely, you can allow implicit conversions on either a left or a right operand by implementing the overload as a free function:
employee operator+(employee const &a, employee const &b) {
return employee(a.salary + b.salary);
}
Since salary
is private, you would/will have to declare this operator as a friend of the class for it to work.
You usually want to do one of these or the other. If implicit conversions make sense, then you probably want to support them on both operands. If they don't make sense, then you probably want to prohibit them entirely. The middle ground -- a +
that can convert one operand but not the other rarely makes much sense.
Then again, I'd argue that supporting addition on employees doesn't make sense anyway. It would not be immediately obvious to me (or I think most readers) that adding two employee
s would yield a third employee
object containing the sum of the two employee
s' salaries, with the rest of the data invalid. In fact, I'd argue that you probably shouldn't allow creation of such an invalid employee
object at all.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments