Using two constructors on one object - c++

I have a User class that has two constructors. When I create an object and use the two constructors, one of them gives me an error saying: no match for call to '(User) (double&, double&, double&)'
class User
{
public:
int UserAge;
double netIncome, totalSavings, totalDebt;
string UserName;
//Constructor for name and age
User(string name, int age)
{
UserName = name;
UserAge = age;
}
//Constructor for money info
User(double income, double savings, double debt)
{
netIncome = income;
totalSavings = savings;
totalDebt = debt;
}
};
Main:
int main()
{
string Name, answer;
int Age;
double Income, Savings, Debt, Cost, goalCount;
cout << setw(82) << "--------------------------------------------------------------" << endl;
cout << setw(75) << "Hello and welcome to the RS Money Management App." << endl << endl;
cout << setw(76) << "Designed to help you be responsible with your money!" << endl;
cout << setw(82) << "--------------------------------------------------------------" << endl << endl;
cout << setw(45) << "Please Enter Your Name: "; cin >> Name;
cout << endl;
cout << setw(44) << "Please Enter Your Age: "; cin >> Age;
User newUser(Name, Age); //object created
cout << endl;
system ("CLS");
cout << "------------------------------" << endl;
cout << setw(15) << "Welcome, " << newUser.UserName << "." << endl;
cout << "------------------------------" << endl;
cout << "Let's start by asking you some simple questions." << endl << endl;
Goals financialGoals[10];
cout << "What is your current monthly net Income? "; cin >> Income;
cout << "How much are you currently saving? "; cin >> Savings;
cout << "Do you have Debts? "; cin >> answer;
if (answer == "yes")
{
cout << "What amount of debt must you pay? "; cin >> Debt;
}
else if (answer == "no")
{
cout << "Great." << endl << endl;
Debt = 0;
}
newUser(Income, Savings, Debt); //2nd constructor, where error is occuring
I am not sure what I am doing wrong. Am I not supposed to use two constructors on one object? Am I missing something?

You are trying to call a non-existent operator() on an existing User object, expecting it to call the 2nd constructor. That is not how constructors work. They can only be used to create new objects, not modify objects.
So, you need to either:
create a new, separate object, eg:
User newUser2(Income, Savings, Debt);
Otherwise, if your intent is to modify an existing object, then you will have to add additional methods to handle that task, eg:
class User
{
public:
int UserAge;
double netIncome, totalSavings, totalDebt;
string UserName;
User()
{
setUserInfo("", 0);
setMoneyInfo(0, 0, 0);
}
//Constructor for name and age
User(string name, int age)
{
setUserInfo(name, age);
setMoneyInfo(0, 0, 0);
}
//Constructor for money info
User(double income, double savings, double debt)
{
setUserInfo("", 0);
setMoneyInfo(income, savings, debt);
}
void setUserInfo(string name, int age)
{
UserName = name;
UserAge = age;
}
void setMoneyInfo(double income, double savings, double debt)
{
netIncome = income;
totalSavings = savings;
totalDebt = debt;
}
};
Then you can do things like this:
User newUser(Income, Savings, Debt);
...
newUser.setUserInfo(Name, Age);
User newUser(Name, Age);
...
newUser.setMoneyInfo(Income, Savings, Debt);
User newUser;
...
newUser.setUserInfo(Name, Age);
newUser.setMoneyInfo(Income, Savings, Debt);

Am I not supposed to use two constructors on one object?
Correct.
Picture this. You are in charge of a construction crew. You are sent to an empty field to build a house. You go with your crew, build the house, and return home. Fully routine. Shortly after that, you are sent to the same field -- no longer empty -- to build a house. In the same location as the house that is currently there. How would you do that?
You cannot. Not unless you destroy the existing house first. Same thing with objects. Once constructed, an object cannot be re-constructed unless it is destroyed first. You can replace an object (e.g. using assignment), but not re-construct it.
If you need to construct your object in stages, use a constructor plus a setter. If you don't have a setter, then you cannot contruct your object in stages. Instead, you would need to keep the data in separate variables until you can call a constructor with all the data an object is supposed to hold.
User newUser(Name, Age);
newUser.setIncome(Income);
newUser.setSavings(Savings);
newUser.setDebt(Debt);
// Or a combo setter like
newUser.setFinances(Income, Savings, Debt);
Or
User newUser(Name, Age, Income, Savings, Debt);
If your intent is really to replace the existing object with a new one (losing the name and age information), you could define an assignment operator and assign a new object to the old. This would call the constructor a second time, but the second time is for a new (unnamed, temporary) object. After the assignment, the new object is destroyed, but a copy (or move) of its data is retained by the original object. The end result is similar to destroying the original object and constructing a replacement in the same place.
User newUser(Name, Age);
newUser = User(Income, Savings, Debt); // Name and Age are lost
Caveat: This assumes the traditional semantics for assignment, which is not enforced by the language.

Related

Error:C2679 binary '==': no operator found which takes a right-hand operand of type 'const std::string' (or there is no acceptable conversion

I have written my code for an employee management system that stores Employee class objects into a vector, I am getting no errors until I try and compile, I am getting the error: C2679 binary '==': no operator found which takes a right-hand operand of type 'const std::string' (or there is no acceptable conversion). But I am not sure why any help would be great, Thank you!
// Employee Management System
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
class Employee
{
public:
Employee();
string GetName();
string GetStatus();
float GetSalary();
int GetAge();
int GetYearHired();
private:
string m_Name;
string m_Status;
float m_Salary;
int m_Age;
int m_YearHired;
};
Employee::Employee()
{
m_Salary = 0;
m_Age = 0;
m_YearHired = 0;
}
string Employee::GetName()
{
string fName;
string lName;
cout << "Please enter the new employee's first name: ";
cin >> fName;
cout << "Please enter the new employee's last name: ";
cin >> lName;
m_Name = fName + lName;
return m_Name;
}
string Employee::GetStatus()
{
string status;
cout
<< "Please enter the employee's status (full time, part time, or manager): ";
cin >> status;
return m_Status;
}
float Employee::GetSalary()
{
float salary;
cout << "Please enter the employee's salary: ";
cin >> salary;
return m_Salary;
}
int Employee::GetAge()
{
int age;
while (true)
{
cout << "Please enter the employee's age: ";
cin >> age;
if (age > 0)
break;
else
cout << "Error: Please enter a positive value.";
}
return m_Age;
}
int Employee::GetYearHired()
{
int yearHired;
cout << "Please enter what year the employee was hired: ";
cin >> yearHired;
return m_YearHired;
}
class Staff
{
vector<Employee*> emps;
vector<Employee*>::const_iterator iter;
public:
Staff();
virtual ~Staff();
void Add();
void Remove();
void Clear();
void Display();
};
Staff::Staff()
{
emps.reserve(20);
}
Staff::~Staff()
{
Clear();
}
void Staff::Add()
{
Employee* emp = new Employee;
emp->GetName();
emp->GetStatus();
emp->GetSalary();
emp->GetAge();
emp->GetYearHired();
emps.push_back(emp);
}
void Staff::Remove()
{
Employee* emp;
cout << "Which employee would you like to remove?";
emp->GetName();
iter = find(emps.begin(), emps.end(), emp->GetName()); // Trying to find the employee in the datbase.
if (iter != emps.end()) // If the employee is found in the vector it is removed.
{
cout << "\n" << *iter << " was removed\n\n";
emps.erase(iter); // removes employee from the vector.
}
else // If the employee is not found in the vector, it tells the user that the employee was not found.
{
cout << "Employee not found, please choose anoter employee.\n\n";
}
}
void Staff::Clear()
{
cout << "\nDo you really want to clear all employees? (yes/no)\n"; // Asking the user if they want to clear the database.
string response;
// Storing the response of the user.
cin >> response; // Getting the users response (yes/no).
if (response == "yes") // If response is yes.
{
vector<Employee*>::iterator iter = emps.begin(); // Declares an iterator for the emps vector and sets it to the beginning of the vector.
for (iter = emps.begin(); iter != emps.end(); ++iter) // Iterates through vector.
{
delete *iter; // Deletes the iterators in the vector, freeing all memory on the heap.* iter = 0;
// Sets iterator to zero so it does not become a dangling pointer.
}
emps.clear(); // Clear vector of pointers.
}
else // If response is no.
{
cout << "\nAll employee's remain in the database.\n";
}
}
void Staff::Display()
{
Employee* emp;
if (emps.size() == 0) // Checking to see if the database is empty.
cout
<< "\nThere are no employee's in the database, add employee's to view them here.\n ";
else // If the cart contains any items.
{
cout << "\nThe database contains: \n";
for (iter = emps.begin(); iter != emps.end(); ++iter) // Displaying the inventory.
{
cout << "-------------------------------------------------";
cout << "Employee's Name : " << emp->GetName() << endl;
cout << "Employee's Status : " << emp->GetStatus() << endl;
cout << "Employee's Salary : " << emp->GetSalary() << endl;
cout << "Employee's Age : " << emp->GetAge() << endl;
cout << "Year employee was hired : " << emp->GetYearHired() << endl;
cout << "-------------------------------------------------";
}
}
}
int main()
{
int option = 0;
Staff stf;
// Welcoming the user to the Employee Management System program.
cout
<< "Welcome to our Employee Management System! To get started see the menu options below :\n ";
// Main loop
while (option != 5) // The loop will repeat until the user enters 5 as the option.
{
cout << "------------------------------------------------------------------------------------- - ";
cout << "\nMenu Options: \n";
cout << "\nTo select an option, please type in the number that corresponds to that option.\n ";
cout << "1 - Add an Employee\n2 - Remove an Employee\n3 - Clear the database\n4 - Display Employee's in Database\n5 - Quit" << endl;
cout << "\nWhat would you like to do? ";
cout << "------------------------------------------------------------------------------------- - ";
// Start of the validity check.
bool validInput = false;
while (!validInput) // The loop will repeat until the users input is valid.
{
cin >> option; // User inputs first option choice.
validInput = true; // Assign the input as valid.
if (cin.fail()) // Tests to make sure the value assigned is valid for the variable type.
{
cout << "\nPlease choose a menu option by number\n";
cin.clear(); // Clears stream error.
cin.ignore(numeric_limits<streamsize>::max(), '\n'); // Removes an invalid characters.
validInput = false; // Sets the input back to false, repeats the loop.
}
}
switch (option)
{
case 1:
{
stf.Add();
break;
}
case 2:
{
stf.Remove();
break;
}
case 3:
{
stf.Clear();
break;
}
case 4:
{
stf.Display();
break;
}
case 5: // If option = 5.
cout << "\nThank you for using the Employee Management Program!\n";
// Thanks the user for using the Employee Management program.
break;
default: // If the user does not put in a valid option, it tells them to try again.
cout << "\nThat's not a valid option. Please try again.\n";
break;
}
}
system("pause");
return 0;
}
Problem
std::find is going to compare the Employee *s in emps against the std::string that is returned by GetName. There is no comparison operator defined for Employee * that does this. We can make one, but because the behaviour of GetName is to Get and name for the user, not simply return the Employee's name this will quickly become a mess.
Solution
First Stop storing pointers to Employees in the vectors. This simple change will eliminate the vast majority of your past, present and future pain. In general, use new as little as possible (Why should C++ programmers minimize use of 'new'?) and when you do find yourself needing new, prefer a smart pointer.
vector<Employee*> emps;
becomes
vector<Employee> emps;
that has a ripple effect through your code, not the least of which is
void Staff::Add()
{
Employee* emp = new Employee;
emp->GetName();
emp->GetStatus();
emp->GetSalary();
emp->GetAge();
emp->GetYearHired();
emps.push_back(emp);
}
must become
void Staff::Add()
{
Employee emp;
emp.GetName();
emp.GetStatus();
emp.GetSalary();
emp.GetAge();
emp.GetYearHired();
emps.push_back(emp);
}
But also look into emplace_back and strongly consider getting the user input and then constructing emp around it.
bool operator==(const Employee & rhs) const
{
return m_Name == rhs.m_Name;
}
or a friend function
bool operator==(const Employee & lhs,
const Employee & rhs)
{
return lhs.m_Name == rhs.m_Name;
}
and then change the call to find to compare Employees
iter = find(emps.begin(), emps.end(), emp); // Trying to find the employee in the datbase.
This may lead to more problems because iter is a const_iterator and a member variable (Rubber Ducky wants a word with you about this). Also completely ignores the fact that there are a few dozen more logical mistakes in the the code.
It seems to me (EDIT: had a commented out) string response; declaration before
cin >> response; // Getting the users response (yes/no).
Hope this points you in the right direction
EDIT:
It's there but it's commented out. Try:
cout << "\nDo you really want to clear all employees? (yes/no)\n";
// Asking the user if they want to clear the database.
string response;
// Storing the response of the user.
cin >> response; // Getting the users response (yes/no).
if (response == "yes") // If response is yes.
And I'd double check all the code to avoid the comments interfering with the code

c++ instantiate several classes if a condition is true

Is there a way I can make this work?
I want to create 5 instances of bank if age is greater than 17, but I am getting this error:
[Error] no matching function for call to 'Bank::Bank()'
I need to get this right for my assignment in school.
#include <iostream>
#include <string>
using namespace std;
class Bank{
string Fullname;
string StateOfOrigin;
int Age;
public:
Bank(string name, string state, int age){
Fullname = name;
StateOfOrigin = state;
Age = age;
}
string getname(){
return Fullname;
}
string getstate(){
return StateOfOrigin;
}
int getage(){
return Age;
}
};
int main(){
Bank customer[20];
int x,y,z,age;
string name;
string state;
cout<<"==============================="<<endl;
cout<<"Welcome To Hojma Bank.Plc"<<endl;
cout<<"How many accounts do you want to create? \n";
cin>>y;
for(int k = 0; k < y; k++){
cout<<"Please input your fullname"<<endl;
cin>>name;
cout<<"Please input your state of origin"<<endl;
cin>>state;
cout<<"Please input your age";cout<<endl;
cin>>age;
if(age >= 18){
Bank customer[y](name,state,age);
cout << customer[y].getname();
}
}
}
Bank customer[20];
Here you default-construct twenty Bank objects (oddly called customer??). Or, at least, you tried to, but your Bank class has no default constructor. Neither should it, from what I can tell.
Bank customer[y](name,state,age);
cout << customer[y].getname();
Here I guess you tried to "declare" individual array elements, but it doesn't work like that.
Also your usage of y is wrong; you can accept y maximum, but you probably meant to use the current loop counter value, k. That's broken too because you have a filter on age so you might skip some array elements.
Why not use a nice tasty std::vector, and add new customers at will? Then you can also get rid of those confusing ints, half of which you're not even using.
int main()
{
int y = 0;
cout << "===============================\n";
cout << "Welcome To Hojma Bank.Plc\n";
cout << "How many accounts do you want to create?" << endl;
cin >> y;
std::vector<Bank> customers;
for (int i = 0; i < y; i++) {
int age;
string name;
string state;
cout << "Please input your full name" << endl;
cin >> name;
cout << "Please input your state of origin" << endl;
cin >> state;
cout << "Please input your age" << endl;
cin >> age;
if (age >= 18){
customers.emplace_back(name,state,age);
cout << customer.back().getname();
}
}
}
You could do with some error checking on your user input, too. And rename that class to Customer.
If you create an array of objects (Bank customer[20]), the class needs to have a default constructor. Just define something like this:
Bank() : Fullname(""), StateOfOrigin(""), Age(0) {}

Simple bank account program does not store the balance correctly

I'm currently wrapping up my bank account program, but I've ran into some problems en route to completion. The problem seems pretty easy to resolve, but I can't quite wrap my head around how I should go about actually fixing it.
I'll first include the assignment below:
Implement a class Account. An account has a balance, functions to add and withdraw money, and a function to inquire the current balance. Pass a value into a constructor to set an initial balance.
If no value is passed the initial balance should be set to $0.
Charge a $5 penalty if an attempt is made to withdraw more money than available in the account.
Enhance the Account class to compute interest on the current balance.
Implement a class Bank. This bank has two objects, checking and savings, of the type Account that was developed in the preceding exercise.
Implement four instance methods:
deposit(double amount, String account)
withdraw(double amount, String account)
transfer(double amount, String account)
printBalances()
Here the account string is "S" or "C". For the deposit or withdrawal, it indicates which account is affected. For a transfer it indicates the account from which the money is taken; the money is automatically transferred to the other account.
The only problem appears to be with actually storing the information for each account in the balance variable in the Account.cpp file. It just stays at 0, and that's why I feel this issue should be easy to fix. I'd imagine I'm just forgetting something very basic about class implementations, but that is why I am here! Now that I think about it, I think part of my confusion comes from the fact that I've implemented similar programs before but used only arrays instead of variables, and I did not experience this same problem. The data seemed to get stored into the array regardless, so this may be my problem? The code follows:
Account.h:
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
class Account
{
public:
Account();
Account(double balance);
void Add(double money);
void Withdraw(double money);
double GetBalance();
private:
double balance;
};
Account.cpp:
#include "Account.h"
// Penalty Fee Constant
const double PENALTY_FEE = 5.00;
Account::Account()
{
balance = 0.00;
}
Account::Account(double money)
{
balance = money;
}
void Account::Add(double money)
{
balance += money;
}
void Account::Withdraw(double money)
{
if(money > balance)
balance += PENALTY_FEE;
else
balance -= money;
}
double Account::GetBalance()
{
return balance;
}
Bank.cpp:
#include "Account.h"
void deposit(double, string);
void withdraw(double, string);
void transfer(double, string);
void printBalances();
int main()
{
string accountChoice;
int selection;
double transaction = 0;
// !!!!!!!!!!!!!!!!!!HAVE TO STILL COMPUTE INTEREST!!!!!!!!!!!!!!!!
cout << fixed << showpoint << setprecision(2);
do
{
cout << "Please make a selection:" << endl;
cout << "1.) Deposit" << endl;
cout << "2.) Withdraw" << endl;
cout << "3.) Transfer" << endl;
cout << "4.) Print balances" << endl;
cout << "5.) Quit" << endl;
cin >> selection;
if(selection == 1)
{
cout << endl << "Please select the account you would like to perform operations on(S or C):" << endl;
cin >> accountChoice;
cout << endl << "Please enter the amount to be deposited:" << endl;
cin >> transaction;
cout << endl;
deposit(transaction, accountChoice);
}
else if(selection == 2)
{
cout << endl << "Please select the account you would like to perform operations on(S or C):" << endl;
cin >> accountChoice;
cout << endl << "Please enter the amount to be withdrawn:" << endl;
cin >> transaction;
cout << endl;
withdraw(transaction, accountChoice);
}
else if(selection == 3)
{
cout << endl << "Please select the account you would like to perform operations on(S or C):" << endl;
cin >> accountChoice;
cout << endl << "Please enter the amount to be transferred:" << endl;
cin >> transaction;
cout << endl;
transfer(transaction, accountChoice);
}
else if(selection == 4)
printBalances();
else
cout << "Closing program -- Thank you for using the ATM teller!" << endl;
}while(selection != 5);
system("pause");
return 0;
}
void deposit(double amount, string account)
{
Account savings, checking;
if(account == "S" || account == "s")
savings.Add(amount);
else
checking.Add(amount);
}
void withdraw(double amount, string account)
{
Account savings, checking;
if(account == "S" || account == "s")
savings.Withdraw(amount);
else
checking.Withdraw(amount);
}
void transfer(double amount, string account)
{
Account savings, checking;
if(account == "S" || account == "s")
{
savings.Withdraw(amount);
checking.Add(amount);
}
else
{
checking.Withdraw(amount);
savings.Add(amount);
}
}
void printBalances()
{
Account savings, checking;
cout << "The current balance in savings is: " << savings.GetBalance() << endl;
cout << "The current balance in checking is: " << checking.GetBalance() << endl << endl;
}
I think it might be clearer overall if you declare another class 'Customer', and give them a name, customer number and a checking and saving account each. The Customers should be instantiated somewhere with process lifetime so that they are not deleted, eg. in a static container, eg std::map.
ATM, (sorry!), you seem to have some non-member functions that instantiate accounts, do things with them and then they are deleted upon function return.
You are creating a new Account object every time you need it. Of course it will be 0 when you print it as the default constructor initializes the balance to 0.
Rather when the App starts, as the user to identify his account or something and create a corresponding account instance. The instance need to be there throughout the whole time user operates on it.
So instantiate not in the methods but in the main function. And pass the instance to the methods as a way of modifying the instance as required.

C++ basic menu driven program (calling functions)

I'm new to programming and am trying to figure out why this is happening.
Basically I'm asked to design a menu driven program that does some basic deposit/withdrawal calculations. I'm supposed to write different functions for each process and call on them when necessary.
I'm having 2 problems:
1) My functions aren't updating my variables within the program. For example it will run, I can enter my starting balance, I can enter my transaction type and amount but every time I switch from deposit to writing a check, it resets the balance to the original user input.
2) When I want the program to exit, it is still asking me for the double input. Not sure how to make it accept just an "E" instead of "E number"
Thanks in advance.
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
//Prototypes for my functions that will be called in
void displayMenu();
double checkProcess(double, double);
double depositProcess(double, double);
double totalServCharge(double);
int main()
{
//Variables needed for the problem
char choice; //menu choice
double transAmt, balance, numbServCharge; //transaction amount, current balance, total service charges, number of service charges
numbServCharge = 0; //Start the counter for number of service charges at zero
cout << "Checkbook Program\n\n";
cout << "Enter the beginning balance: ";
cin >> balance; //get the initial balance
cout << endl;
do
{
//Call the display menu function
displayMenu();
//Get user's choice and transaction amount from menu
cout << "Enter a transaction: ";
cin >> choice >> transAmt;
choice = toupper(choice);
cout << endl;
//Create an error message for invalid choice and get a second choice
while((choice != 'C') && (choice != 'D') && (choice != 'E'))
{
cout << "Invalid selection. Please choose C, D or E: ";
cin >> choice;
}
//Set up for option #1 -- using a check
if(choice=='C')
{
//Call check function and service charges function
checkProcess(transAmt, balance);
totalServCharge(numbServCharge);
}
//Set up for option #2 -- deposits
if(choice=='D')
{
//Call deposit function and service charges function
depositProcess(transAmt, balance);
totalServCharge(numbServCharge);
}
}while(choice != 'E'); //Close program if option 3 is selected
//Display final balance
cout << "Processing end of the month";
cout << "\nFinal balance : $ " << fixed << setprecision(2) << balance << endl << endl;
system("pause"); //Pause screen so it doesn't close right away
return 0;
}
void displayMenu()
{
//Highlight menu options
cout << "\nCommands\n";
cout << "C amount - process a check in a specific amount\n";
cout << "D amount - process a deposit in a specific amount\n";
cout << "E - end the program\n\n";
}
double checkProcess(double transAmt, double balance)
{
cout << "\nProcessing check for $" << fixed << setprecision(2) << transAmt;
transAmt = transAmt + .25; //Add the service charge onto the transaction
balance = balance - transAmt; //Update account balence
cout << "\nBalance: $" << fixed << setprecision(2) << balance;
cout << "\nService charge: $0.25 for a check\n";
return balance;
}
double depositProcess(double transAmt, double balance)
{
cout << "\nProcessing Deposit for $" << fixed << setprecision(2) << transAmt << endl;
transAmt = transAmt - 0.25; //Add the service charge onto the deposit
balance = balance + transAmt; //Update account balence
cout << "Balance: $" << fixed << setprecision(2) << balance << endl;
return balance;
}
double totalServCharge(double numbServCharge)
{
double totalServCharge = 0;
numbServCharge++; //Add one to the number of service charges there have been
totalServCharge = .25 * numbServCharge; //Update total cost of service charges
cout << "Total service charges: $" << fixed << setprecision(2) << totalServCharge << endl; //Tell user total service charges so far
return numbServCharge;
}
(1) Your variables aren't updating because you aren't changing them; you're changing the copies passed to your subroutines. You either need to pass the current balance by reference (so that when you change it in the subroutine scope, you're also changing the original) or assign the return value from your subroutines to your current balance.
When you pass a variable by value (as you are now), the program makes a copy of that variable for use in the function scope. When you leave that scope, the copy is deleted. Do this when you want to be sure a subroutine won't alter anything in the scope from which it is called. If you want the subroutine to alter the variables you pass to it, pass the variables by reference. In this function signature, "transAmt" is passed by value and "balance" is passed by reference:
double foo(double transAmt, double& balance);
Incidentally, if you pass the balance by reference there's no reason to return it. You aren't doing anything with the returned value right now anyway.
(2) If you want to not ask for a number when "E" is given, make separate "cin" statements for the number in the conditional blocks for "C" and "D". Right now all your input code is shared between all cases. It would be even better if you arrange things so that you exit the loop before a number is asked for. This way, you only have to write that "cin" statement once.
It's becouse in C++ when you call a function with parameter, you only operate on COPIES of those parameters. If you want to change the original value, pass variable as reference.
See those simple examples:
#include <iostream>
using namespace std;
void normal(int a)
{
a += 10;
}
void by_reference(int &a) //Notice ampersand
{
a += 10;
}
int by_return(int a)
{
return a + 10;
}
int main()
{
int a = 5;
cout << "Start: " << a <<endl;
normal(a);
cout << "Normal: " << a <<endl;
by_reference(a);
cout << "Reference: " << a <<endl;
a = by_return(a);
cout << "Return: " << a <<endl;
}
Now you can see that if you pass the variable as reference it gets changed.
Even if just putting the & before parameter names would fix your problem, I'd recommend you using a return, it generally is simplier and makes your code look better (it's much easier to understand).
Also, correct your indentation. It's very bery important when you work with bigger projects.
Hope this helps. :)
1 | The first problem is occurring because you are not actually modifying the user's input. You are passing the variable in but once the new value is returned you are not storing it, thus the value is forgotten in the main function. Not the best solution, but it might suit you to do this:
if (choice == 'D')
{
//Call deposit function and service charges function
balance = depositProcess(transAmt, balance); // Overwrite balance
numbServCharge = totalServCharge(numbServCharge); // Overwrite numbServCharge
}
Or in a more efficient way, you can pass in the variable by reference. All you would need to do is change the function prototype.
void totalServCharge(double&);
void depositProcess(double&, double&);
Now when the variable is passed in, it will be modified directly by the function. Also note the function data type changed to void because you no longer need to return a value from the function.
2 | Your second problem is the way you handle user input. If you want to ask for multiple input, it might sometimes be best to do it with separate cout and cin statements.
The way it is set in your program is for the user to enter two inputs at once, therefore if you only enter E, it waits patiently as it should for your next input (transAmt). It might be better to process the action desired and then have an amount entered afterwards.
Very general example:
do {
cout << "1 : Transaction or 2 : Exit" << endl;
cin >> choice;
if (choice == 2)
break;
cout << "1. Deposit\n" << "2. Check" << endl;
cout << "Enter transaction type followed by amount" << endl;
cin >> transType >> amount;
// Then do what was specified in choice
} while (true); // Or whatever condition pleases you

C++ Return Statement Not Working

I've just started learning C++ and i've been having problems implementing return statements. I've been easily able to pass data to a new function but I am having no joy in getting it to return.
I've written the simplest code I could think of to try and debug what is going wrong and I still can't work it out. I am NOT trying to pass too many return values and I have a correct function type to pass too. It just doesn't seem to work?
I am using Xcode 4 on a Macbook Pro:
#include <iostream>
using namespace std;
int agenext (int age);
int main ()
{ int age;
cout << "What's Your Age? \n";
cin >> age;
cout << "Your Current Age: " << age;
agenext(age);
cout << endl << "A year has passed your new age is: ";
cout << age;
}
int agenext (int x)
{
x++;
cout << endl << "Your Next Birthday is " << x;
return x;
}
It's returning perfectly find. You just aren't setting the value it returns to anything.
age = agenext(age)
Is what you are looking for, or you could pass a pointer or a reference to the age variable.
returning is only half the battle, the other half is assigning that value to something. Consider changing:
agenext(age);
to
age = agenext(age);
Both the existing answers are correct; if you want to return a value, it needs to be assigned somewhere.
For future reference, you can also do what you want by skipping the return and passing age by reference instead of value.
void agenext (int &x)
{
x++;
cout << endl << "Your Next Birthday is " << x;
/* the value change WILL show up in the calling function */
}
In your main function, you need another variable to hold the new age that is return from the age function.
int main ()
{ int age, newAge;
cout << "What's Your Age? \n";
cin >> age;
cout << "Your Current Age: " << age;
newAge = agenext(age);
cout << endl << "A year has passed your new age is: ";
cout << newAge;
return 0;
}