The problem is on line 35 in the "Balance" class where I am trying to use "Menu menu;" which is the constructor for the Menu class.
1 2 3 4
elseif (theChoice == 3)
{
Menu menu;
}
Here you create a new "local" Menu object with "automatic" storage duration, but it will be destroyed immediately after construction, because your variable menu obviously goes out of scope right away!
If you want the Menu object to live as long as the enclosing Balance object, then you have to make menu a member variable of the Balance class, not a local variable in the choice() method.
Example:
1 2 3 4 5 6 7 8 9
class Balance
{
private:
int theChoice = 0;
double USD = 0, Peso = 0, AUD = 0, Bit = 0, Yen = 0;
double USF = 0, PF = 0, AUF = 0, BF = 0, YF = 0;
Menu menu; // <-- !!!
/* ... */
How would I go about running that then if the user chooses to? (chooses choice 3)
What about something like:
1 2 3 4
elseif (theChoice == 3)
{
menu.doSomething();
}
...assuming that the Menu class has a method doSomething() which you want to call when the user has chosen 3. Or maybe add a more general method to Menu that takes the choice value as argument:
double addUSD()
{
try
{
cout << "How much USD would you like to add: ";
cin >> USD;
if (USD < 0.01)
{
throw 0;
}
}
catch (int e)
{
if (e == 0)
{
cout << "Amount must be at least $0.01" << endl;
addUSD();
}
}
return USD;
}
is not really good practice as you are using exceptions for normal input validation. Usually you would do this in a loop like this:
1 2 3 4 5 6 7 8 9
double addUSD() {
double USD{};
do {
cout << "How much USD would you like to add (> 0.01): ";
cin >> USD;
} while ((USD < 0.01) && (cout << "Amount must be at least $0.01\n"));
return USD;
}
and similar for other functions.
Exceptions are meant to be used for truly exceptional run-time errors and not for just usual input validation.
Exceptions are meant to be used for truly exceptional run-time errors and not for just usual input validation.
I imagine the upper end of "truly exceptional" contains things like "CPUStruckByHalleysCometException" and "UniversalHeatDeathException", but what does the lower end look like? In other words if run-time errors can be measured on a scale from "ordinary" to "truly exceptional", what is the most "ordinary" run-time error you can think of that is still "truly exceptional"?
In my opinion the problem with OP's use of exceptions isn't that they are used for "usual input validation" but that they are killing flies with a cannon by using them for local flow control within tiny functions.