My assignment for my college C++ class was to create a pseudo piggy bank in wwhich you can add or withdraw change, and then print out the balance. My Professor gave us a mostly finished header file and a file with a main method to test our program. Our assignment was to create a seperate c++ file so that would create the methods designated in the header file that would give the same outputs as his test file. I've gotten the program to compile and run, but it gives me garbage outputs (like a penny count of -1). For some reason, my constructor does not zero my fields, and I need a little help.
This is the header file he gave us. I'll leave a comment to what I added.
#ifndef PIGGYBANK_H
#define PIGGYBANK_H
class PiggyBank
{
public:
PiggyBank(int p, int n, int d, int q);
PiggyBank(); //I added this
int getPenniesCount() const; // Return number of pennies in bank.
int getNickelsCount() const;
int getDimesCount() const;
int getQuartersCount() const;
PiggyBank& addPennies(int p); // Add Pennies to bank and return reference.
PiggyBank& addNickels(int n);
PiggyBank& addDimes(int d);
PiggyBank& addQuarters(int q);
int withdrawPennies(int p); // Withdraw pennies, return num withdrawn.
int withdrawNickels(int n);
int withdrawDimes(int d);
int withdrawQuarters(int q);
void displayBalance() const;
void breakTheBank(); // Display the balance then cash out (all counts zeroed).
private: // I added these
int pennies;
int nickels;
int dimes;
int quarters:
};
#endif
This the other part of the code. For convenience sake, I'll just give you the methods for quarters, and the constructor, because the methods for nickels, dimes, etc. are identical to the quarter methods.
To expand on what ne555 is saying is that you should not put 'int' in front of your variables in your default constructor. Basically you are declaring new variables in the constructor that get assigned to zero and when the constructor returns, those variables are no longer in scope. Just take out the 'int' keywords from PiggyBank(), and that should fix it.