Simple member function involving coins

I am trying to write a member function for a class I have. The class is called Coins, and acts as a coin purse that keeps track of how many quarters, nickes, dimes, pennies.

for example, the constructor is Coins(int q, int d, int n, int p)
where each int represents the respective coin.

I am trying to write a member function
void deposit_coins(Coins & c)

where you can deposit coins from one Coin object to another so:

Coins c(1,1,1,1);
Coins c2(2,2,2,2);
c2.deposit_coins(c);

Now c has 0,0,0,0 and c2 has 3,3,3,3

I am having trouble doing the addition/subtraction between each object.

It should be simple enough but I am just not seeing it.
Any help?

closed account (48T7M4Gy)
Any help?

No, none here. No expertise in problems involving the universe at large or in general. Specificity has an unerring ability to change that situation.
Illustrating as a class method as described in OP:
1
2
3
4
5
6
7
8
9
10
11
12
13
14

std::vector<Coins> Coins::deposit_coins(Coins& c)
{
	quarters += c.quarters;//transferring coins
	nickels += c.nickels;
	dimes += c.dimes;
	pennies += c.pennies;
	c.quarters = 0;//setting Coins c coins to 0 
	c.nickels = 0;
	c.dimes = 0;
	c.pennies = 0;
	std::vector<Coins> vecC {*this, c};
	return vecC;//return by copy since local object
}

In case you don't care about the state of c after the transfer and only want to return *this object then you can omit the steps that set Coins c coins to 0 and return just *this

The following uses a coin class to discuss operator overloading and might also be of interest:
http://umich.edu/~eecs381/handouts/Operator_Overloading.pdf
closed account (48T7M4Gy)
In all seriousness Coins should be renamed Purse and without vectors try this for a quick start. Feel free to fill in the blanks:

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
#include <iostream>

class Purse{
private:
    int penny = 0;
    int nickel = 0;
    
public:
    Purse (int aNickel, int aPenny) {
        penny = aPenny;
        nickel = aNickel;
    }
    
    double dollars() {
        double money = (penny + nickel * 5)/100.0;
        return money;
    }
    
    Purse operator+ (Purse rhs) {
        this -> penny += rhs.penny;
        this -> nickel += rhs.nickel;
        
        return *this;
    }
};


int main()
{
    Purse a(5,5), b(3,1);
    
    std::cout << a.dollars() << '\n';
    std::cout << b.dollars() << '\n';
    std::cout << (a+b).dollars() << '\n';
    
    return 0;
}
0.3
0.16
0.46
Program ended with exit code: 0
Last edited on
Topic archived. No new replies allowed.