Help understanding operator overloading?

Im having a really hard time understanding how this section of code works. I get everything in the program besides the adding part and it seems no matter how many time a re-read the section in my book or watch videos I simply dont get it. Please try to explain it as simple as possible.

Money Money::operator+(Money& amount2)
{
double sum = dollars + amount2.dollars;
return Money(sum);

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
  #include "stdafx.h"
#include <iostream>
#include <cstdlib>
#include <cmath>
using namespace std;

//Class for amounts of money in U.S. currency.
class Money
{
public:
	Money();
	Money(double amount);
	double getDollars();
	void setDollars(double amount);
	Money operator+(Money& amount2);

private:
	double dollars;

};
int main()
{
	Money yourAmount, myAmount(100.00);
	yourAmount.setDollars(3.5);
	cout << "Your amount is " << yourAmount.getDollars() << endl;
	cout << "My amount is " << myAmount.getDollars() << endl;
	Money ourAmount = yourAmount + myAmount;
	cout << yourAmount.getDollars() << " + " << myAmount.getDollars() << " equals "
		<< ourAmount.getDollars() << endl;
	system("pause");
	return 0;
}

Money Money::operator+(Money& amount2)
{
double sum = dollars + amount2.dollars;
return Money(sum);
}
Money::Money()
{
	dollars = 0;
}
Money::Money(double amount)
//: dollars(dollarsPart(amount)), cents(centsPart(amount))
{
	dollars = amount;
}
double Money::getDollars()
{
	return dollars;
}
void Money::setDollars(double amount)
{
	dollars = amount;
}


Last edited on
Operator overloading is not much different from regular function overloading. It's just that the syntax is a bit more confusing.

An alternative way of writing yourAmount + myAmount is to write yourAmount.operator+(myAmount). Think of operator+ as being the function. yourAmount is the object that the function is called on. myAmount is the argument that is passed to the function.
Topic archived. No new replies allowed.