How can I access elements of a vecotor in C++ - c++

Actually, I am rookie, and I started to learning this language a few months age. Now, I confronted with an insoluble issue. I devised a program to get information of numerous employee's specification and store it in a vector. In order to acquire better performance, I designed a class named "Employee", and defined a function to give some options to user, like adding new employee, promotion a specific employee's salary and so on.
I defined my matching criterion through operators, but there is an error in program, and that is when I want to display, the output is completely weird. it looks like a some kind of Chinese letter :-)
here is my code:
Thanks
My major problem is when it comes displaying employee's specification
#include <iostream>
#include <string>
#include <vector>
#include <memory>
#include <sstream>
using namespace std;
class Employee
{
public:
Employee(string FirstName, string LastName, int age , double Salary, bool Status ) ://constructor
fName(FirstName), lName(LastName), EmpAge(age), EmpSalary(Salary), RecruitmentStatus(Status) {};
void setSalary(const double&);
void SetRecruitmentStatus(const bool&);
void Promote(const double&);
//====================================//
operator const char* ()
{
ostringstream formattedOutput;
formattedOutput << this->fName.c_str() << " " << (this->lName.c_str()) << " | " << this->EmpAge << " | " << this->EmpSalary << ((RecruitmentStatus) ? "Working" : "Fired");
string output = formattedOutput.str();
return output.c_str();
}
bool operator == (const Employee& anotherEmployee)const
{
return (this->lName == anotherEmployee.lName);
}
bool operator < (const Employee& anotherEmployee)const
{
return (this->EmpSalary < anotherEmployee.EmpSalary);
}
private:
string fName, lName;
int EmpAge;
double EmpSalary;
bool RecruitmentStatus;
};
void Employee::setSalary(const double& income)
{
this->EmpSalary += income;
}
void Employee::SetRecruitmentStatus(const bool& Status)
{
this->RecruitmentStatus = Status;
}
void Employee::Promote(const double& Promotion)
{
this->EmpSalary += Promotion;
}
template <typename T>
void displayElements(T& input)
{
for (auto iterator = input.begin();
iterator != input.end(); iterator++)
{
cout << *iterator << endl;
}
}
void selection(int&);
Employee getNewEmp(void);
int main()
{
vector<Employee> Records;
int ID;
do
{
selection(ID);
switch (ID)
{
case 1:
{
Records.push_back(getNewEmp());
break;
}
case 2:
{
cout << "please enter last name of the employee you want to change his/her recruitment'status: ";
string lastName; cin >> lastName; cout << endl;
auto memberLocation = find(Records.begin(), Records.end(), lastName.c_str());
break;
}
case 3:
{
cout << "please enter last name of the employee you want to promote his/her recruitment'salary: ";
string lastName; cin >> lastName; cout << endl;
auto memberLocation = find(Records.begin(), Records.end(), lastName.c_str());
break;
}
default:
{
if (ID !=4)
{
cout << "Wrong selection!\nThe program will be closed after a few seconds\n";
exit(1);
}
}
}
} while (ID != 4);
displayElements(Records);
cout << "Thanks for using this program\n";
return 0;
}
void selection(int& input)
{
system("cls");
cout << "please Choose one of these option:\n"
"1. add a new employee\n"
"2. changing an employee status\n"
"3. Promote an employee's salary\n"
"4. exit : ";
cin >> input;
}
Employee getNewEmp(void)
{
system("cls");
string firstName, lastName;
cout << "first name:"; cin >> firstName; cout << endl;
cout << "last name:"; cin >> lastName; cout << endl;
int age;
cout << "Age: "; cin >> age; cout << endl;
double salary;
cout << "Offered Salary: "; cin >> salary; cout << endl;
bool Status;
cout << "Is he/she working(1) or got fired(0) : "; cin >> Status; cout << endl;
return Employee(firstName, lastName, age, salary, Status);
}

Related

Why is the balance not getting updated after Deposit or Withdraw?

I am a beginner in C++ and I come from a non-CS background. I was making this project of a Bank Management System using C++, but I am facing a problem. Whenever I am Depositing or withdrawing money, it is not getting updated when I do "2 Balance Enquiry". Can anyone help me understand why it is so and also How to fix it? I am new to this so please forgive me if this is a stupid question. Thanks
Here is my code:
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <vector>
#include <map>
using namespace std;
//*************** C U S T O M E R ***************
class Customer {
string fname, lname;
long accno;
float balance;
static long count;
public:
Customer() {}
Customer(string fn, string ln, float b) {
count++;
fname = fn;
lname = ln;
balance = b;
accno = count;
}
long getaccno() {
return accno;
}
void greetnewcx() {
cout << "Hello, " << fname << " " << lname << endl;
cout << "Account Successfully Created. Account Number: " << getaccno();
cout<<"\nBalance: Rs." << balance;
}
void deposit(float dep) {
balance += dep;
cout << "Successfully deposited\nNew Balance: Rs." << balance;
}
void greeting() {
cout << "Hello, " << fname << " " << lname << endl;
}
void withdraw(float withdraw) {
balance -= withdraw;
cout << "Successfully withdrawn\nRemaining Balance: Rs." << balance;
}
friend ostream& operator<<(ostream& out, Customer& c);
};
long Customer::count = 0;
//*************** B A N K ***************
class Bank {
map<long, Customer> accounts;
public:
Bank() {
Customer account;
}
Customer open_account(string f, string l, float b);
void show_allaccounts();
void show_balance(long acno);
void deposit(long acno);
void withdraw(long acno);
void removeacc(long acno);
};
//*************** M A I N ***************
int main() {
Bank b;
Customer cx;
int choice;
string fname, lname;
long accountNumber;
float balance;
do {
cout << "\n\n\tSelect one option below ";
cout << "\n\t1 Open an Account";
cout << "\n\t2 Balance Enquiry";
cout << "\n\t3 Deposit";
cout << "\n\t4 Withdrawal";
cout << "\n\t5 Close an Account";
cout << "\n\t6 Show All Accounts";
cout << "\n\t7 Quit";
cout << "\nEnter your choice: ";
cin >> choice;
switch (choice) {
case 1:
cout << "\nFirst Name: " << endl;
cin >> fname;
cout << "\nLast Name: " << endl;
cin >> lname;
cout << "Initial Balance: Rs." << endl;
cin >> balance;
cx = b.open_account(fname, lname, balance);
break;
case 2:
cout << "Enter Account Number: ";
cin >> accountNumber;
b.show_balance(accountNumber);
break;
case 3:
cout << "Enter Account Number: ";
cin >> accountNumber;
b.deposit(accountNumber);
break;
case 4:
cout << "Enter Account Number: ";
cin >> accountNumber;
b.withdraw(accountNumber);
break;
case 5:
cout << "Enter Account Number: ";
cin >> accountNumber;
b.removeacc(accountNumber);
break;
case 6:
b.show_allaccounts();
break;
case 7:
break;
default:
cout << "\nEnter corret choice";
exit(0);
}
} while (choice != 7);
return 0;
}
//*************** F U N C T I O N S **************
Customer Bank::open_account(string f, string l, float b) {
Customer cx(f, l, b); //calling constructor of Class Customer
accounts.insert(pair<long,Customer>(cx.getaccno(), cx));
cx.greetnewcx();
return cx;
};
void Bank::show_balance(long acno) {
map<long, Customer> ::iterator itr;
itr = accounts.find(acno);
cout << itr->second << endl;
}
void Bank::deposit(long acno) {
map<long, Customer> ::iterator itr;
itr = accounts.find(acno);
auto cx = itr->second;
cx.greeting();
cout << "\nEnter the amount to deposit: Rs.";
float d;
cin >> d;
cx.deposit(d);
}
void Bank::withdraw(long acno) {
map<long, Customer> ::iterator itr;
itr = accounts.find(acno);
auto c = itr->second;
c.greeting();
cout << "\nEnter the amount to withdraw: Rs.";
float d;
cin >> d;
c.withdraw(d);
}
void Bank::removeacc(long acno) {
accounts.erase(acno);
cout << "Account Deleted.";
}
void Bank::show_allaccounts() {
map<long, Customer> ::iterator itr;
for (itr = accounts.begin(); itr != accounts.end(); itr++) {
cout <<"Account No. " <<itr->first<< endl;
cout << itr->second<<endl;
}
}
//*************** OPERATOR OVERLOADED F U N C T I O N S **************
ostream& operator<<(ostream& out, Customer& c) {
out << c.fname << " " << c.lname << endl;
out << "Balance: Rs." << c.balance << endl << endl;
return out;
}
cx = b.open_account(fname, lname, balance);
This makes a copy of the Customer. You now have one Customer in cx and another one inside the map. You then modify the copy you stored in cx leaving the one inside the map untouched.
You do this elsewhere too:
Customer Bank::open_account(string f, string l, float b) {
Customer cx(f, l, b); //calling constructor of Class Customer
accounts.insert(pair<long,Customer>(cx.getaccno(), cx));
cx.greetnewcx();
return cx;
};
Here, you create a Customer in cx, but then you create another Customer inside the accounts structure (that's what insert does), then you return yet another Customer because cx goes out of scope. You only wanted to create one customer but you created three.
In sum, your code does this:
It creates a new Customer with Customer cx(....
It puts a copy of that Customer in the map with insert.
It returns a copy of that Customer using return.
The calling code than initializes an existing Customer to the value of the returned copy with cx = b.open_account....
You really only wanted one Customer, not four.

How should we add function inside a structure?

#include <iostream>
using namespace std;
struct teacher
{
int id;
char name[50];
int salary;
void input(teacher a)
{
cout << "Enter Name : ";
cin >> a.name;
cout << "Enter ID : ";
cin >> a.id;
cout << "Enter Salary : ";
cin >> a.salary;
}
void output(teacher b)
{
cout << "Your Name Is : " << b.name << endl;
cout << "Your ID Is : " << b.id << endl;
cout << "Your Salary Is : " << b.salary;
}
};
int main()
{
teacher t;
t.input(t);
t.output(t);
return 0;
}
Is there any problem? The output is random numbers, don't know what is it.
I tried writing the output function separately, but still same results.
This seems like a weird design, why don't your class methods directly operate on this?
struct teacher
{
int id;
std::string name;
int salary;
void input()
{
cout << "Enter Name : ";
cin >> name;
cout << "Enter ID : ";
cin >> id;
cout << "Enter Salary : ";
cin >> salary;
}
void output() const
{
cout << "Your Name Is : " << name << endl;
cout << "Your ID Is : " << id << endl;
cout << "Your Salary Is : " << salary;
}
};
Then main would look like
int main()
{
teacher t;
t.input();
t.output();
return 0;
}
Also I'd prefer to use std::string instead of char[] when possible.
In input() you modify parameter a which goes out of scope when it reaches the end of the function.
Instead you should modify the class members variables themselves.
void input()
{
cout << "Enter Name : ";
cin >> name;
cout << "Enter ID : ";
cin >> id;
cout << "Enter Salary : ";
cin >> salary;
}

C++ Virtual Void

Okay, so I have a parent class called employee and 3 subclass called manager,researcher and engineer. I made a vector and want to list them. this is the how I process the making.
vector <Employee*,Manager*> EmployeeDB;
Employee *temp;
temp = new Manager(first, last, salary, meetings, vacations);
EmployeeDB.push_back(temp);
I have no problem in making the vector, my concern is listing the info. all 3 subclasses have firstname, lastname and salary but they're difference is that they have different data members which is unique, example the Manager has the int value vacation and the Engineer has the int value experience so on and so forth.
Employee.h:
#include <iostream>
#include <string>
using namespace std;
#ifndef EMPLOYEE_h
#define EMPLOYEE_h
class Employee
{
public:
Employee();
Employee(string firstname, string lastname, int salary);
string getFname();
string getLname();
int getSalary();
virtual void getInfo();
private:
string mFirstName;
string mLastName;
int mSalary;
};
#endif
Employee.cpp:
#include "Employee.h"
#include <iostream>
#include <string>
using namespace std;
Employee::Employee()
{
mFirstName = "";
mLastName = "";
mSalary = 0;
}
Employee::Employee(string firstname, string lastname, int salary)
{
mFirstName = firstname;
mLastName = lastname;
mSalary = salary;
}
string Employee::getFname()
{
return mFirstName;
}
string Employee::getLname()
{
return mLastName;
}
int Employee::getSalary()
{
return mSalary;
}
void Employee::getInfo()
{
cout << "Employee First Name: " << mFirstName << endl;
cout << "Employee Last Name: " << mLastName << endl;
cout << "Employee Salary: " << mSalary << endl;
}
Main:
#include <vector>
#include <iostream>
#include <string>
#include "Employee.h"
#include "Engineer.h"
#include "Manager.h"
#include "Researcher.h"
using namespace std;
vector <Employee*> EmployeeDB;
Employee *temp;
void add()
{
int emp, salary, vacations, meetings, exp, c;
string first, last, type, school, topic;
bool skills;
do
{
system("cls");
cout << "===========================================" << endl;
cout << " Add Employee " << endl;
cout << "===========================================" << endl;
cout << "[1] Manager." << endl;
cout << "[2] Engineer." << endl;
cout << "[3] Researcher." << endl;
cout << "Input choice: ";
cin >> emp;
system("cls");
} while (emp <= 0 || emp > 3);
cout << "===========================================" << endl;
cout << " Employee Info " << endl;
cout << "===========================================" << endl;
cout << "Employee First name: ";
cin >> first;
cout << "Employee Last name: ";
cin >> last;
cout << "Employee Salary: ";
cin >> salary;
switch (emp)
{
case 1:
cout << "Employee numbers of meetings: ";
cin >> meetings;
cout << "Employee numbers of vacations: ";
cin >> vacations;
temp = new Manager(first, last, salary, meetings,vacations);
EmployeeDB.push_back(temp);
delete temp;
break;
case 2:
cout << endl;
cout << "[1]YES [2]NO" << endl;
cout << "Employee C++ Skills: ";
cin >> c;
if (c == 1)
{
skills = true;
}
else
{
skills = false;
}
cout << "Employee Years of exp: ";
cin >> exp;
cout << "(e.g., Mechanical, Electric, Software.)" << endl;
cout << "Employee Engineer type: ";
cin >> type;
temp = new Engineer(first, last, salary, skills, exp, type);
EmployeeDB.push_back(temp);
delete temp;
break;
case 3:
cout << "Employee School where he/she got his/her PhD: ";
cin >> school;
cout << "Employee Thesis Topic: ";
cin >> topic;
temp = new Researcher(first, last, salary, school, topic);
EmployeeDB.push_back(temp);
delete temp;
break;
}
}
void del()
{
}
void view()
{
for (int x = 0; x < (EmployeeDB.size()); x++)
{
cout << EmployeeDB[x]->getInfo();
}
}
void startup()
{
cout << "===========================================" << endl;
cout << " Employee Database " << endl;
cout << "===========================================" << endl;
cout << "[1] Add Employee." << endl;
cout << "[2] Delete Employee." << endl;
cout << "[3] List Employees." << endl;
cout << "[4] Exit." << endl;
cout << "Please Enter Your Choice: ";
}
int main(int argc, char** argv)
{
bool flag = true;
int choice;
do {
do
{
system("cls");
system("pause>nul");
startup();
cin >> choice;
} while (choice < 0 || choice >4);
switch (choice)
{
case 1:
add();
break;
case 2:
del();
break;
case 3:
view();
break;
case 4:
flag = false;
system("EXIT");
break;
}
} while (flag == true);
return 0;
system("pause>nul");
}
I am getting error on the view() function.
It says no operator<< matches these operands
binary '<<': no operator found which takes a right hand operand of type void etc etc.
The problem is that the getInfo has return type void and you are trying to put that return value into cout.
It's important to understand that the code std::cout << val actually calls the function operator<<(ostream& out, const objectType& val) where objectType is the type of 'val'.
In your case the type is void, and there is simply no implementation of operator<< that takes void as a type. hence the error "no operator found which takes a right hand operand of type void...".
In order to fix your issue you have a few options:
Change view() to be
for (...)
{
EmployeeDB[x]->getInfo();
}
Change getInfo() to return a string the info as you'd like:
std::string getInfo()
{
std::string info;
info =...
return info;
}
Create an operator<< for Employee and change view to call it:
view()
{
for (...)
{
std::cout << EmployeeDB[x];
}
}

Create a vector of base class objects and store derived class objects within

I am trying to create an employee database (Vector of Employees). There are 3 types of employees ie. employees is the base class and Manager, Engg and Scientist are derived class.
Every employee has first name and last name. In addition to the name, each of the 3 types of employees have unique stats ie. Manager has number of meetings/week whereas the Engg has work experience and so on.
I have a couple of questions
1. Should I upcast the derived objects to the base class or downcast the base class to the derived class?
2. How do I use polymorphism to override methods, since I want the user to add an employee type and based on the type selected the respective entry fields should appear ie. in case of a Manager, in addition to the first and last names, the program should also ask for meetings/week?
Here is my Class file
class Employee{
public:
Employee();
Employee(string fName, string lName, int sal);
virtual void printEmp();
string getFirstName();
string getLastName();
protected:
string m_fName;
string m_lName;
int m_sal;
};
class Manager : public Employee{
public:
Manager();
Manager(string fName, string lName, int sal, int meets, int hols);
void printEmp();
protected:
int m_meets;
int m_hols;
};
Here is the implementation
Employee::Employee(){
m_fName = "Default";
m_lName = "Default";
m_sal = 0;
}
Employee::Employee(string fName, string lName, int sal){
m_fName = fName;
m_lName = lName;
m_sal = sal;
}
void Employee::printEmp(){
cout << "First Name: " << m_fName << endl
<< "Last Name: " << m_lName << endl
<< "Salary: " << m_sal << endl;
}
string Employee::getLastName(){
return m_lName;
}
string Employee::getFirstName(){
return m_fName;
}
Manager::Manager(string fName, string lName, int sal, int meets, int hols) : Employee(fName, lName, sal), m_meets(meets), m_hols(hols)
{
//empty
}
void Manager::printEmp(){
Employee::printEmp();
cout << "Meets/Week: " << m_meets << endl
<< "Holidays/Year: " << m_hols << endl << endl;
Here is the main
int main(){
bool exit = false;
vector<Employee*> dBVector;
while (!exit){
cout << "Welcome to Employee Database, Enter an option to continue..." << endl;
cout << "1) Add an Employee, 2) Delete an Employee, 3) Save Database, 4) Exit" << endl;
int input;
cin >> input;
string fNameInp;
string lNameInp;
int salInp;
string lNameSearch;
int i; // for loop in Delete employee case
bool deleted = false;
switch (input){
case 1: //Add
cout << "1) Add a Manager, 2) Add an Engg, 3) Add a Researcher" << endl;
int empInput;
cin >> empInput;
if (empInput == 1){
cout << "Enter First Name: ";
cin >> fNameInp;
cout << "Enter Last Name: ";
cin >> lNameInp;
cout << "Enter Salary: ";
cin >> salInp;
cout << "Number of meetings/week: ";
int meetsInp;
cin >> meetsInp;
cout << "Number of holidays/year: ";
int holsInp;
cin >> holsInp;
Manager mEmp(fNameInp, lNameInp, salInp, meetsInp, holsInp);
Employee &emp = mEmp;
dBVector.push_back(&mEmp);
dBVector[dBVector.size()-1]->printEmp();
}
else if (empInput == 2){
cout << "Enter First Name: ";
cin >> fNameInp;
cout << "Enter Last Name: ";
cin >> lNameInp;
cout << "Enter Salary: ";
cin >> salInp;
cout << "Cpp Experience (Y/N): ";
string cppInp;
cin >> cppInp;
cout << "Years of experience: ";
float expInp;
cin >> expInp;
cout << "Engg Type (Chem, Mech, IT): ";
string typInp;
cin >> typInp;
Engg eEmp(fNameInp, lNameInp, salInp, cppInp, expInp, typInp);
Employee &emp = eEmp;
dBVector.push_back(&eEmp);
dBVector[dBVector.size() - 1]->printEmp();
}
else if (empInput == 3){
cout << "Enter First Name: ";
cin >> fNameInp;
cout << "Enter Last Name: ";
cin >> lNameInp;
cout << "Enter Salary: ";
cin >> salInp;
cout << "School of PhD: ";
string schoolInp;
cin >> schoolInp;
cout << "Topic of PhD: ";
string topImp;
cin >> topImp;
Researcher rEmp(fNameInp, lNameInp, salInp, schoolInp, topImp);
Employee &emp = rEmp;
dBVector.push_back(&rEmp);
dBVector[dBVector.size() - 1]->printEmp();
}
break;
case 2: // Delete Emp
for (int x = 0; x < dBVector.size(); x++){
dBVector[x]->getLastName();
cout << endl;
}
cout << "Input Last name of the employee to delete: " << endl;
cin >> lNameSearch;
for (i = 0; i < dBVector.size(); i++){
if (dBVector[i]->getLastName() == lNameSearch){
dBVector.erase(dBVector.begin() + i);
cout << dBVector[i]->getFirstName() << "has been deleted from database";
deleted = true;
break;
}
}
if (deleted == false && i == dBVector.size()){
cout << "No Employee with Last Name - " << lNameSearch << " exists in Database." << endl;
}
else
break;
case 3: //save
cout << "saving..." << endl;
break;
case 4: //exit
exit = true;
break;
}
}
}
Please Help!
Firstly, if you want to use polymorphism you need to store pointers in your vector. As the vector is the sole owner of the employees something like std::vector<std::unique_ptr<Employee>> would be suitable.
Edit: I see you have updated the vector to use pointers. But you are storing a pointer to a local stack allocated object, e.g mEmp. This will not work, when the mEmp variable goes out-of-scope at the closing brace the object will be deleted and you will be left with a dangling pointer in your vector that points to a deleted object. Using this dangling pointer is undefined behaviour. You need to allocate the Manager on the heap using new. Then the object will not be deleted when the variable goes out-of-scope but you do need to remember to delete the object when you are done. Something like unique_ptr makes this easy.
Regarding your questions:
Try to minimize explicit casting, especially downcasting. At the point that you store the Employee in the vector it will be implicitly upcast from the derived class to Employee but other than that there is not much need for casting.
You have roughly the right idea when it comes to overriding methods, if you call the virtual printEmp method on an Employee pointer it will call the override in the derived class.
If you are happy for the user input to be the responsibility of the Employee classes you could simply add a virtual method that initializes the employee using suitable input from the user. But I would be tempted to keep that separate from your domain objects. You need a switch statement on the user choice of employee type anyway so polymorphism doesn't gain you much there.
If you really want to use polymorphism for the employee creation I would suggest using something like the Abstract Factory pattern.
Here is my suggestion anyway:
#include <vector>
#include <string>
#include <iostream>
#include <memory>
class Employee {
public:
Employee(std::string fName, std::string lName, int sal);
virtual ~Employee();
virtual void printEmp();
protected:
std::string m_fName;
std::string m_lName;
int m_sal;
};
class Manager : public Employee {
public:
Manager(std::string fName, std::string lName, int sal, int meets, int hols);
void printEmp() override;
protected:
int m_meets;
int m_hols;
};
Employee::Employee(std::string fName, std::string lName, int sal)
: m_fName(fName), m_lName(lName), m_sal(sal) {
}
Employee::~Employee() {
}
void Employee::printEmp(){
std::cout << "First Name: " << m_fName << "\n"
<< "Last Name: " << m_lName << "\n"
<< "Salary: " << m_sal << "\n";
}
Manager::Manager(std::string fName, std::string lName, int sal, int meets, int hols)
: Employee(fName, lName, sal), m_meets(meets), m_hols(hols){
}
void Manager::printEmp(){
Employee::printEmp();
std::cout << "Meets/Week: " << m_meets << "\n"
<< "Holidays/Year: " << m_hols << "\n";
}
std::unique_ptr<Manager> createManager() {
std::cout << "Enter First Name: ";
std::string fNameInp;
std::cin >> fNameInp;
std::cout << "Enter Last Name: ";
std::string lNameInp;
std::cin >> lNameInp;
std::cout << "Enter Salary: ";
int salInp;
std::cin >> salInp;
std::cout << "Number of meetings/week: ";
int meetsInp;
std::cin >> meetsInp;
std::cout << "Number of holidays/year: ";
int holsInp;
std::cin >> holsInp;
std::cout << "\n";
return std::make_unique<Manager>(fNameInp, lNameInp, salInp, meetsInp, holsInp);
}
std::unique_ptr<Employee> createEmployee() {
int input;
std::cout << "1) Add a Manager, 2) Add an Engg, 3) Add a Researcher\n";
std::cin >> input;
switch (input){
case 1:
return createManager();
default:
return nullptr;
}
}
int main() {
std::vector<std::unique_ptr<Employee>> dBVector;
std::cout << "Welcome to Employee Database, Enter an option to continue...\n";
std::cout << "1) Add an Employee"
<< ", 2) Delete an Employee"
<< ", 3) Save Database"
<< ", 4) Exit\n";
int input;
std::cin >> input;
switch (input){
case 1:
dBVector.push_back(createEmployee());
break;
default:
break; // Do nothing
}
dBVector.at(0)->printEmp();
}
Live demo
You may want to store pointers in the vector to avoid slicing, as others mentioned. Then each employee could have their own input method and ask the right questions to initialize themselves (main would not implement that but only call the respective employee's virtual input function). Input and output are conceptually sysmmetrical operations which hints at implementing them symmetrically, i.e. in this case both as member functions.

Error LNK2019 - Unsure how to fix (1 unresolved external) [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
I am nearly done with this program, however I am getting an error that I am unsure how to deal with. I have looked for other solutions but none have seemed to help
The error I'm getting is:
error LNK2019: unresolved external symbol "void __cdecl deposit(class customer * const,int)" (?deposit##YAXQAVcustomer##H#Z) referenced in function _main
C:\Users\D\Desktop\Programs\Project 3\DProject3\Debug\DProject3.exe : fatal error LNK1120: 1 unresolved externals
It seems to have something to do with the deposit function, however I have tried fooling around with it to no avail, if anyone could help it would be much appreciated, I have 3 files for this project
Header
#ifndef CUSTOMER_H
#define CUSTOMER_H
#include <string>
struct Date
{
int Day;
int Month;
int Year;
};
struct Name
{
std::string first_name;
std::string middle_name;
std::string last_name;
};
class customer
{
private:
Date birth_date;
Name name;
float balance_saving, balance_checking, initial_saving, initial_checking, amount, account_type;
public:
customer(); //Customer constructor
customer(Date birth_date, Name name, float initial_saving, float initial_checking); // Customer constructor with info
void withdraw(float amount, int account_type);
void deposit(float amount, int account_type);
float check_balance_saving(); // Print out the savings balance on screen
float check_balance_checking(); // Print out the checking balance on screen
void setDate(int Day, int Month, int Year);
Date getDate();
void setName(std::string first_name, std::string middle_name, std::string last_name);
Name getName();
void setSaving(float initial_saving);
void setChecking(float initial_checking);
};
#endif
Implementation File
#include "customer.h"
//Contructor without info / Default info
customer::customer()
{
birth_date.Day = 01;
birth_date.Month = 01;
birth_date.Year = 1901;
name.first_name = "N/A";
name.middle_name = "N/A";
name.last_name = "N/A";
balance_saving = 0;
balance_checking = 0;
}
// Constructor with user input data
customer::customer(Date DMY, Name FML, float initSav, float initCheck)
{
birth_date = DMY;
name = FML;
initial_saving = initSav;
initial_checking = initCheck;
}
void customer::withdraw(float amtW, int accW)
{
amount = amtW;
account_type = accW;
}
void customer::deposit(float amtD, int accD)
{
amount = amtD;
account_type = accD;
}
float customer::check_balance_saving()
{
return initial_checking;
}
float customer::check_balance_checking()
{
return initial_checking;
}
void customer::setDate(int Day, int Month, int Year)
{
birth_date.Day = Day;
birth_date.Month = Month;
birth_date.Year = Year;
}
Date customer::getDate()
{
return birth_date;
}
void customer::setName(std::string First, std::string Middle, std::string Last)
{
name.first_name = First;
name.middle_name = Middle;
name.last_name = Last;
}
Name customer::getName()
{
return name;
}
void customer::setSaving(float setSav)
{
initial_saving = setSav;
}
void customer::setChecking(float setCheck)
{
initial_checking = setCheck;
}
Main
#include "customer.h"
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
//Function prototypes
void withdraw (customer[], int);
void deposit (customer[], int);
void checkBal (customer[], int);
void newAccountFile (customer[], int);
int main ()
{
customer custInfo[49]; //Creates the customer array for info to be stored in
int customerAmt = 0; //Keeps track of the amount of customers in the array
ifstream customerfile ("account.dat"); //Open existing customer file
while (customerAmt < 2) //Loop to read the data from the existing file
{
int D, M, Y; // Birth day, month, year
string FN, MN, LN; //First name, middle name, last name
float Save, Check; //Savings & Checking initial amount
customerfile >> D;
customerfile >> M;
customerfile >> Y;
customerfile >> FN;
customerfile >> MN;
customerfile >> LN;
customerfile >> Save;
customerfile >> Check;
custInfo[customerAmt].setDate(D, M, Y);
custInfo[customerAmt].setName(FN, MN, LN);
custInfo[customerAmt].setSaving(Save);
custInfo[customerAmt].setChecking(Check);
customerAmt++;
}
customerfile.close(); //Close customer file and end file reading
//Variables for the User menu
int accountNumber, option, D1, M1, Y1;
string FN1, MN1, LN1;
float Save1, Check1;
//Loop used for User menu
do
{
cout << "1. withdraw" << endl;
cout << endl;
cout << "2. Deposit" << endl;
cout << endl;
cout << "3. Check Balances" << endl;
cout << endl;
cout << "4. Create a New Account" << endl;
cout << endl;
cout << "0. Exit" << endl;
cin >> option;
if (option == 1) // Uses withdraw function
{
cout << "Enter the account number: ";
cin >> accountNumber;
withdraw(custInfo, accountNumber);
}
else if (option == 2) // Uses deposit function
{
cout << "Enter the account number: " << endl;
cin >> accountNumber;
deposit(custInfo, accountNumber);
}
else if (option == 3) // Uses check balance function
{
cout << "Enter the account number: " << endl;
cin >> accountNumber;
checkBal(custInfo, accountNumber);
}
else if (option == 4) //Option to handle creating a new account
{
cout << "Enter the new account information, starting with birth info: " << endl;
cin >> D1 >> M1 >> Y1;
custInfo[customerAmt].setDate(D1, M1, Y1);
cout << endl;
cout << "Enter the new customer's full name: " << endl;
cin >> FN1 >> MN1 >> LN1;
custInfo[customerAmt].setName(FN1, MN1, LN1);
cout << endl;
cout << "Enter the inital savings balance: " << endl;
cin >> Save1;
custInfo[customerAmt].setSaving(Save1);
cout << endl;
cout << "Enter the initial checking balance: " << endl;
cin >> Check1;
custInfo[customerAmt].setChecking(Check1);
customerAmt++;
}
}while (option != 0);
newAccountFile(custInfo, customerAmt); // Creates new updated account info file
system ("pause");
return 0;
}
void withdraw(customer custInfo[], int number)
{
float withdrawAmount;
int optionWit;
float tempSave;
float tempCheck;
cout << "1. Withdraw from savings" << endl;
cout << endl;
cout << "2. Withdraw from checking" << endl;
cin >> optionWit;
cout << "Enter the amount to be withdrawn: ";
cin >> withdrawAmount;
if (optionWit == 1)
{
tempSave = custInfo[number].check_balance_saving() - withdrawAmount;
custInfo[number].setSaving(tempSave);
}
else if (optionWit == 2)
{
tempCheck = custInfo[number].check_balance_checking() - withdrawAmount;
custInfo[number].setChecking(tempCheck);
}
}
void desposit(customer custInfo[], int number)
{
float depositAmount;
int optionDep;
float tempSave;
float tempCheck;
cout << "1. Deposit to savings" << endl;
cout << endl;
cout << "2. Deposit to checking" << endl;
cin >> optionDep;
cout << "Enter the amount to be deposited: ";
cin >> depositAmount;
if (optionDep == 1)
{
tempSave = custInfo[number].check_balance_saving() + depositAmount;
custInfo[number].setSaving(tempSave);
}
else if (optionDep == 2)
{
tempCheck = custInfo[number].check_balance_checking() + depositAmount;
custInfo[number].setChecking(tempCheck);
}
}
void checkBal(customer custInfo[], int number)
{
int optionBal;
cout << "1. Check savings balance" << endl;
cout << endl;
cout << "2. Check checking balance" << endl;
cin >> optionBal;
if (optionBal == 1)
{
cout << "Current savings balance is: " << custInfo[number].check_balance_saving() << endl;
}
else if (optionBal == 2)
{
cout << "Current checking balance is: " << custInfo[number].check_balance_checking() << endl;
}
}
void newAccountFile(customer custInfo[], int size)
{
int i;
Date tempDate;
Name tempName;
ofstream newAccountStorage;
newAccountStorage.open ("updated_account.dat"); //Opens new file for updated account info
for (i = 0; i < size; i++);
{
tempDate = custInfo[i].getDate();
tempName = custInfo[i].getName();
newAccountStorage << tempDate.Day << endl;
newAccountStorage << tempDate.Month << endl;
newAccountStorage << tempDate.Year << endl;
newAccountStorage << tempName.first_name << endl;
newAccountStorage << tempName.middle_name << endl;
newAccountStorage << tempName.last_name << endl;
newAccountStorage << custInfo[i].check_balance_saving() << endl;
newAccountStorage << custInfo[i].check_balance_checking() << endl;
}
newAccountStorage.close(); //Closes the file after writing new information
}
You have misprint in your function definition
void desposit(customer custInfo[], int number)
^^^^