I keep receiving -2 as my updated salary - c++

I am doing the following with my program:
1) Write the class definition for a class named Employee with name and salary as employee objects. The class contains two member functions: the constructor and a function that allows a program to assign values to the data members.
2) Add two member functions to the Employee class. One member function should allow any program using an employee object to view the contents of the salary data member. The other member function should allow the program to view the contents of the employee name data member.
3) Add another member function to the Employeeclass. The member function should calculate an employee objects new salary, based on a raise percentage provided by the program using the object. Before calculating the raise, the member function should verify that the raise percentage is greater than or equal to zero. If the raise percentage is less than zero, the member function should display an error message.
4) Write a main function that will create an array of employee objects, assign values to the objects, display the names and current salaries for all objects, ask user for the raise percentage and then calculate and display new salaries for all objects.
However, I receive -2 as my new salary after I input the data from the keyboard. I figured another set of eyes could see what I can't and would highly appreciate if someone can lend a hand, or at least steer me in the right direction. Perhaps it is a logic error, or something wrong with my declarations. Thank you for your time.
#include <iostream>
#include <cstdlib>
#include <string>
using namespace std;
class EMPLOYEE
{
public:
EMPLOYEE();//
EMPLOYEE(string name, int salary);//
public:
string name;//name to be input
int salary;//salary to be input
int percentage_raise;
int updated_salary;
public:
int enter_values();
int output_values();
int NEW_SALARY();
};
//default constructor
EMPLOYEE::EMPLOYEE()
{
name = "";
salary = 0;
}
//constructor with name/salary variables
EMPLOYEE::EMPLOYEE(string NAME, int SALARY)
{
name= NAME;
salary= SALARY;
}
//name and salary to be input...
int EMPLOYEE::enter_values()
{ cout<<"Enter name and salary: ";
cin>> name;
cin>>salary;
return 0;
}
//output
int EMPLOYEE::output_values()
{ cout<<"Name: "<<name<<endl;
cout<<"Salary: "<<salary<<endl;
return 0;
}
//
int EMPLOYEE::NEW_SALARY()
{
if ( percentage_raise >= 0)
{ int updated_salary;
int raise= (salary *percentage_raise)/100;
updated_salary += raise;
}
else if(percentage_raise< 0)
{ cout<<"Error Message"<<endl;
}
return 0;
}
int main()
{
EMPLOYEE employees[100];
EMPLOYEE percent_to_be_raised;
int i;
for(i =0 ;i<100 ; i++)
{ employees[i]=EMPLOYEE();
employees[i].enter_values();
employees[i].name;
employees[i].salary;
// employees[i].NEW_SALARY();
employees[i].output_values();
cout<<"How much should the salary be raised by?"<<endl;
cin>>percent_to_be_raised.percentage_raise;
cout<<"-----------------------------"<<endl;
cout<<employees[i].name <<"'s new salary is "<<percent_to_be_raised.updated_salary<<endl;
}
}

You need to rewrite this quite alot.
A few pointers:
EMPLOYEE percent_to_be_raised;
Is completely off base. The task states that this calculation should be done in an employee member function. I.e. the raise should be performed as
Employee alfred;
std::cin>> alfred.salary;
double raise;
std::cin>> raise;
alfred.raise_salary(raise); // this is what the task asks for.
Use a naming convention.
Employee
is fine for a c++ class with a capitalized class name convention. EMPLOYEE is not; this looks like a macro name.
Member function usually starts with non-capitalized
Employee::new_salary( the_salary );
Follow the examples you have available from the course material.
Of course
employees[i].name;
employees[i].salary;
Does not do anything. Please review your code in detail and start at the first spot you don't understand.

Note that the OP coding style convention is used to assist the OP. I am aware of the proper naming convention for classes, member functions, and class data members (e.g. see the answer by Captain Giraffe for more).
Inside of:
int EMPLOYEE::NEW_SALARY()
{
if ( percentage_raise >= 0)
{ int updated_salary;
int raise= (salary *percentage_raise)/100;
updated_salary += raise;
}
} // added this to close the function properly
there is a locally declared variable, which is typed identically to the public access data member of the same name. What is the intention here?
Most likely it should be coded like so:
int EMPLOYEE::NEW_SALARY()
{
if ( percentage_raise >= 0)
{
int raise = (salary *percentage_raise)/100;
updated_salary += raise;
}
} // added this to close the function properly
There are design considerations for having all class member data public, as well as having an integer for a percentage. From the calculation above, it looks like only values of one, two, three, etc. are allowed for the percentage number. What is the class supposed to do if a raise is 3.75 percent?
The constructor has to set ALL class data members to something meaningful too. For example, the percentage_raise and updated_salary variables are ignored. Most likely the default constructor has to be updated to:
//default constructor
EMPLOYEE::EMPLOYEE()
{
name = "";
salary = 0;
percentage_raise = 0;
updated_salary = 0;
}
The name and salary constructor has to be updated too. It should probably look like (using the style convention posted by the OP):
//constructor with name/salary variables
EMPLOYEE::EMPLOYEE(string NAME, int SALARY)
{
name = NAME;
salary = SALARY;
percentage_raise = 0;
updated_salary = salary;
}

Related

Using vector of a class that contains static member variable

I had an Airplane class and this Airplane had a vector of Seat class named "m_seat".
In the Constructor of my Airplane, I used the number of seats as the needed parameter to resize the m_seat vector size to the requested size of the user. This was my code:
class Seat;
class Airplane {
vector<Seat> m_seat;
public:
Airplane(int);
};
class Seat{
static int m_seatNumber;
public:
Seat() { m_seatNumber += 10; }
};
int Seat::m_seatNumber = 100;
Airplane::Airplane(int numberOfSeats) {
for (int i = 0; i<numberOfSeats; ++i) {
m_seat.push_back();
}
}
int main()
{
Airplane(80);
return 0;
}
But it gave this error.
std::vector<_Ty,_Aloc>::push_back no overload of function takes 0 arguments,
and if this was really the problem, I had no idea what should I have put in my push_back()? So I tried {}
m_seat.push_back({});
and It worked!
Now, I have another problem which is my main problem(SO rule: Ask only one question at a time!) that all seat numbers appear to be increased to the same number! I also used the "resize" member function of the vector, instead of that loop:
m_seat.resize(numberOfSeats);
But the problem (same increase in the number of the m_seatNumber) remains unsolved.
Non-native English Speaker, Sorry.
Disclaimer: This is a "best guess" answer.
If you wanted each seat to have a different, automatically increasing number, you need two values; one non-static, describing each seat, and one static, describing last-used number:
class Seat{
static int lastSeatNumber;
int seatNumber;
public:
Seat() { seatNumber = lastSeatNumber; lastSeatNumber += 10; }
};
int Seat::lastSeatNumber = 100;
That way each seat will receive its distinct number. This design is bad, however, as it doesn't allow e.g. seat number sharing between two airplanes! It also doesn't allow you to "free up" the numbers of seats you're no longer using, and the number can only keep growing. Also copying a Seat, while possible, won't manipulate that number at all. It'd be much better to allow the Airplane class to assign the seat numbers:
class Seat{
int seatNumber;
public:
Seat(int seatNumber) : seatNumber(seatNumber) { }
};
Airplane::Airplane(int numberOfSeats) {
int seatNumber = 100;
const int numberIncrement = 10;
for (int i = 0; i < numberOfSeats; ++i) {
m_seat.push_back(Seat(seatNumber));
seatNumber += numberIncrement;
}
}
This way you can get the old behavior by adding another parameter to the airplane constructor telling it which number to start counting from.

Getting wrong output. Garbage value

Problem is, on execution, the value of roundCost I'm getting is
something like -1220673834. I post the entire program because I'm not
sure where I'm going wrong.
Note: I was asked to take all variables as double type and later,
roundCost should be of type int. So I used type conversion there.
#include<iostream>
using namespace std;
class Restaurant{
private:
double tip, tax,totalCost,mealCost, tipPercent, taxPercent;
int roundCost;
public:
int tipCalc(double)
{
tip=mealCost*(tipPercent/100);
return tip;
}
int taxCalc(double)
{
tax=mealCost*(taxPercent/100);
return tax;
}
int totalCost1()
{
totalCost=mealCost+tip+tax;
return totalCost;
}
int roundCost1(double)
{
roundCost=(int)totalCost;
return roundCost;
}
}; // class ends
int main()
{
double mealCost, tipPercent, taxPercent, totalCost;
int roundCost;
Restaurant ob1;
cout<<"\n Enter mealCost \n";
cin>>mealCost;
cout<<"\n Enter mealtipPercent \n";
cin>>tipPercent;
cout<<"\n Enter mealtaxPercent \n";
cin>>taxPercent;
ob1.tipCalc(tipPercent);
ob1.taxCalc(taxPercent);
ob1.totalCost1();
ob1.roundCost1(totalCost);
cout<<"\n Round of cost is "<<roundCost<<endl;
return 0;
}
One thing you seem to be missing is that variables in your class have a different scope then variables in your main. You set the mealcost in your main from cin but you never passed this variable to the class. I changed this to be done using a constructor that sets the meal cost on creation. In every class you make you should always add a constructor. Also, you should be naming the variables your passing to functions and then using the same name in the function. For example in the tax percent function i pass double t, t is the percent, we then use t in the calculation. Your round cost variable was also private so you needed to output it via a function.
Also int functions will return a value, if you are using this type of function you should be assigning the return variable to something, but since you are just setting things in your class you can use void functions for most. The only time you use a value in the main is in the roundcost so this one is good to have it return a value. As it is int (which i assumed you wanted) it will get no decimal points and it will simply cut off any decimals in the total cost (ie 75.75 would become 75).
#include<iostream>
using namespace std;
class Restaurant{
private:
double tip, tax,totalCost,mealCost;
int roundCost;
public:
Restaurant (double m)
{
mealCost = m;
}
void tipCalc(double t)
{
tip=mealCost*(t/100.0);
}
void taxCalc(double t)
{
tax=mealCost*(t/100.0);
}
void totalCost1()
{
totalCost=mealCost+tip+tax;
}
int roundCost1()
{
roundCost=(int)totalCost;
return roundCost;
}
}; // class ends
int main()
{
double mealCost, tipPercent, taxPercent, totalCost;
int roundCost;
cout<<"\n Enter mealCost \n";
cin>>mealCost;
Restaurant ob1(mealCost);
cout<<"\n Enter mealtipPercent \n";
cin>>tipPercent;
cout<<"\n Enter mealtaxPercent \n";
cin>>taxPercent;
ob1.tipCalc(tipPercent);
ob1.taxCalc(taxPercent);
ob1.totalCost1();
cout<<"\n Round of cost is "<<ob1.roundCost1()<<endl;
return 0;
}
Try to do a bit more research next time by using a debugger, outputting cout statements regularly and searching for the errors you find but this will give you a working code this time.

How do you make a vector of class objects?

I'm a bit confused as to how vectors work. What I'm trying to do is create a vector of 5 TaxBill objects. Then, what I want to do is read from an input file that has the names and different tax rates for 5 states. I want to store the name of the state in the object and the tax rates of the state in an array in int main().
Here's the input file called "Tax Rates.dat". The numbers are the sales, property and income tax rate, respectively, for each state.
TEXAS .0825 .02 -.03
MARYLAND .065 .04 .05
OHIO .03 .025 .03
CALIFORNIA .095 .055 .045
MAINE .02 .015 .02
Here's my class interface called "Tax Bill.h".
using namespace std;
class TaxBill
{
public:
void setValue(string, int);
void dataValid(double&, double&, double&);
private:
string Name;
int index;
double taxBill;
}
Here's my class implementation called "Tax Bill.cpp".
#include "Tax Bill.h"
void TaxBill::setValue(string name, int x)
{}
void TaxBill::dataValid(double& a, double& b, double& c)
{
if(a < 0)
a = 0;
if(b < 0)
b = 0;
if(c < 0)
c = 0;
return;
}
Here's my main source code so far.
#include <iostream>
#include <string>
#include <iomanip>
#include <fstream>
#include <vector>
#include "Tax Bill.h"
using namespace std;
int main()
{
const int SALARY = 100000,
HOUSE = 246000,
PURCHASE = 36000;
ifstream fin;
fin.open("Tax Rates.dat");
vector <TaxBill> someVector (5);
double sales,
property,
income;
double taxRates[5][3];
string name;
if(!fin)
return 0;
else
{
for(int i = 0; fin >> name >> sales >> property >> income; i++)
{
dataValid(sales, property, income);
taxRates[i][0] = sales;
taxRates[i][1] = property;
taxRates[i][2] = income;
}
}
The for loop is where I want to store the name of the state read from the input file and i into the string Name and index of the class object. The reason for the index is because later in the program I want to sort the objects in the vector alphabetically but not the array where the corresponding tax rates are stored.
I also don't want to use the function push_back().
I guess my question is, how do I make an vector of 5 class objects and access them?
Please keep in mind that my program is hardly complete and it's this one hurdle that's holding me back.
Here example of using vector from your code. Here you declare
vector <TaxBill> someVector (5);
So now, you have someVector[0] - [4] (5 in total). To use it, actually you just have to assign it like an normal array.
someVector[0].{insert property here}
But wait, in your class, there is no clear way to set the string Name and Index. So i think you forget to place it here, hence i make my own in the class.
class TaxBill
{
public:
void setValue(string Name, int Index){
name = Name; index = Index;
}
void dataValid(double&, double&, double&);
private:
string name;
int index;
double taxBill;
}
Now to use the vector, i just used the property this way
someVector[0].setValue("someName",1);
Tada, you get it to works. Btw, i dont know why you declare a procedure in the class, but you want to used it multiple times in main program. I mean this one
dataValid(sales, property, income);
to used it, i suggest you make a procedure in main program rather than in class and anyway that line should produce an error anyway. :)

how to make Inheritance dependence

I'm triying to make this exercise:
There are different types of employees: regular
workers,supervisors,board members which are specific types of
supervisors
Track the number of objects of type regular worker.
Each employee has its name and surname and can introduce himself.
Each employee object has its own worker id which is assigned to him
while it is created
The salary is calculated is specific way depending on the type of the
employee.
Each employee can have its direct supervisor which can be any
supervisor(it means that for example a board member can be a
supervisor of regular worker)
Now i had made all of point, exclude the last point:
class Employees
{
public:
static int workerid;
int salary;
Employees(){
workerid += 1;
}
void introduce(){
cout << "the name is:" << name << "and surname" << surname << endl;
}
};
int Employees::workerid = 0;
class Supervisors :public Employees{
public:
Supervisors(){
salary = 1000;
}
};
class BoardMembers : public Supervisors{
public:
BoardMembers(){
salary = 1200;
}
};
class RegularWorkers :public Employees{
public:
static int number;
Supervisors *supervisor;
RegularWorkers(Supervisors supervisor){
this->supervisor = &supervisor;
number += 1;
salary = 600;
}
};
int RegularWorkers::number = 0;
(i think until the last point is ok), but for the last point I need one id of the supervisor but how to made the supervisor or boardemember assign to the regularworker?
Thank you & best regards
Modify the employee class by adding a Supervisor
Supervisor *supervisor;
And then overload the Employee constructor to accept type Supervisor and set them equal to each other.
Employees(Supervisor *s){
supervisor = s;
workerid += 1;
}
Then you can access the Supervisor's ID by using
supervisor->ID
Also you may want to include name and surname as member variables and initialize those as well in the constructor. To add to the previous constructor it might look like this.
Employees(Supervisor *s, string sName, string sSurname){
name = sName;
surname = sSurname;
supervisor = s;
workerid += 1;
}

create an array of class objects in c++

Hi guys I want to make an array of class objects....so that I can keep on creating as many objects during runtime as and when required
I wrote the following code, but its giving me error:
class contact{
public:
string name;//ALL CLASS VARIABLES ARE PUBLIC
int phonenumber;
string address;
contact(){//Constructor
name= NULL;
phonenumber= NULL;
address= NULL;
}
void input_contact_name(string s){//function to take contact name
name=s;
}
void input_contact_number(int x){//function to take contact number
phonenumber=x;
}
void input_contact_address(string add){//function to take contact address
address=add;
}
}
int main(){
contact *d;
d= new contact[200];
string name,add;
int choice;//Variable for switch statement
int phno;
static int i=0;//i is declared as a static int variable
bool flag=false;
cout<<"\tWelcome to the phone Directory\n";//Welcome Message
cout<<"Select :\n1.Add New Contact\n2.Update Existing Contact\n3.Delete an Existing Entry\n4.Display All Contacts\n5.Search for a contact\n6.Exit PhoneBook\n\n\n";//Display all options
cin>>choice;//Input Choice from user
while(!flag){//While Loop Starts
switch(choice){//Switch Loop Starts
case 1:
cout<<"\nEnter The Name\n";
cin>>name;
d[i]->name=name;
cout<<"\nEnter the Phone Number\n";
cin>>phno;
d[i]->input_contact_number(phno);
cout<<"\nEnter the address\n";
cin>>add;
d[i]->input_contact_address(add);
i++;
flag=true;
}
}
return 0;
}
Please can some one out figure out the reason??
Thanks in advance
Many problems:
Missing semicolon on the closing brace of the class, as maverik noted
Use of string without using namespace std; or using std::string; (or #include <string> for that matter)
Ditto #2 for cin and cout (and <iostream>)
d[i]-> is wrong; d[i] is a contact&, not a contact*, so use . instead of ->
name= NULL; and address= NULL; are nonsensical -- string is not a pointer type, and already default-constructs to empty
phonenumber= NULL; is technically valid, but still 'wrong'
Also, good lord, use some whitespace in your code.
EDIT (in response to comment): Your constructor should look like:
contact() : phonenumber() { }
You forget the ;
class contact {
...
}; // <- ; is neccessary