I’m very new to operator operloading concept and the related questions asked before were way ahead of me, so I need to ask a basic question.
Here is the .h file:
#define ACCOUNT_H
using namespace std;
class Account{
friend Account &operator+ (Account &acc);
friend ostream &operator<< (ostream &, Account &);
public:
Account(double=100.0,double=0.0,double=0.0);
Account &returnSum(Account &otherAccount) const;
Account& operator+=(Account &Acc1);
void setT(double);
void setD(double);
void setE(double);
double getT(void);
double getD(void);
double getE(void);
void printAccount();
private:
double t;
double d;
double e;
};
#endif
I need to overload + as a global function “with single argument” (this was the challenging part for me here) and += as member function (here I assume I can’t take the right hand side operand since it is a member function, so that was the problematic part). Here’s my implementation for +=:
Account &Account ::operator+=(Account &Acc1){
Account *result = new Account(Acc1.getT()+t,Acc1.getD()+d,Acc1.getE()+e);
Acc1 = *result;
return *this;
}
I would really appreciate if you could correct this += and write me an implementation for + overloading. I simply need the t,d,e values to be added as an Account object.
If you want
operator+as a free function, you need:Also,
operator +is a binary operator, so it’s impossible for it to only receive one argument. Even when a member function, it takes 2 parameters, just that the first parameter,this, is passed under the hood.So, your two options:
1) Member operator
2) Free operator
Very important 1:
Note that I’m returning by value, not reference as you do. This is to prevent UB, as you’ll probably return a local variable, which is illegal to return by reference.
Very important 2:
This code will leak. Why not use automatic storage variables:
Still not sure about the logic inside, but at least it doesn’t leak memory. The way you have it now, you’re modifying the parameter, not the object you call
+=on. So after, say,a+=b,awill still be the same, andbwill be modified.