Help me understand whats wrong

I have the following code

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
 using namespace std;
#include <vector>
#include <functional>
#include <algorithm>
#include <iostream>
#include <iterator>
template<class rate,class sum> 
	class Add_Interest : public unary_function<sum,void>{
		public : 
	explicit Add_Interest(rate in) : r(in), _sum(0){} 
		void operator()(sum& acc)const {
		rate temp = acc*r/100.0;
		this->_sum += temp;
		acc += temp;
		cout << this->_sum << endl;
		}
		rate get_interest_rate() const {
		return r;
		}
		sum get_interest_sum() const {
		
		return this->_sum;
		}
		private :
		rate r;
		mutable sum _sum;
		
};	
	
template <class rate,class sum> ostream& operator<<(ostream& os ,Add_Interest<rate,sum>& bank){
	os << "Interest rate " << bank.get_interest_rate() << ", total interest delivered: " << bank.get_interest_sum() << endl;

	return os;
}
// Add more headers if required


// Define Add_Interest and operator<< for Add_Interest here.

int main()
{
   vector<long double> accounts;

   accounts.push_back(10000.00);
   accounts.push_back(10000.00);
   accounts.push_back(20000.00);
   accounts.push_back(30000.00);
   accounts.push_back(50000.00);
   accounts.push_back(80000.00);
   Add_Interest<float,long double> rates(5.0);
   cout << rates << endl;
	for_each(accounts.begin(),accounts.end(),rates); 
	cout << rates.get_interest_sum();
   return 0;
}


The problem i have is that when i run for_each, and cout << this->_sum << endl; is run, it displays the intended value, but when i call cout << rates.get_interest_sum(); right after, the value has changed back to its default 0 value, how come?
I can't see where you update member Add_Interest<>.r, so I'd expect it to remain at zero.

Why is void operator()(sum& acc) const const?
Its not r that is the problem, its _sum. _sum is mutable so const doens't effect it(?)
Function for_each (InputIterator first, InputIterator last, Function f); As you see, the function is passed by copy
Ahhh, tnx alot ne555
Topic archived. No new replies allowed.