Arrays in a Class

I was given this payroll code without arrays and tasked with converting it to arrays. When it runs, I am able to input the amount of employees and a first name, but when I try to input a second name I get
Exception thrown at 0x7A5E3B59 (vcruntime140d.dll) in OOP Project.exe: 0xC0000005: Access violation writing location 0xCCCCCCCC.

If there is a handler for this exception, the program may be safely continued.
I don't understand why this happening, please help!

#include "iostream"
#include "string"

using namespace std;

const int X = 50;

class employee {
public:

void setFirstName(string name)
{
fName[X] = name;
}
void setLastName(string name)
{
lName[X] = name;
}
void setHours(double number)
{
hWorked[X] = number;
}
void setWage(double number)
{
wage[X] = number;
}
void setPay()
{
gPay[X] = hWorked[X] * wage[X];
tax *= gPay[X];
nPay[X] = gPay[X] - tax;
}

string getFirstName()
{
return fName[X];
}
string getLastName()
{
return lName[X];
}
double getWage()
{
return wage[X];
}
double getTax()
{
return tax;
}
double getHoursWorked()
{
return hWorked[X];
}
double getGrossPay()
{
return gPay[X];
}
double getNetPay()
{
return nPay[X];
}




private:
double wage[X], hWorked[X], gPay[X], nPay[X];
double tax = .10;
string fName[X], lName[X];


};

int main()
{

employee CS[X];
double number;
string name;
int employees;


cout << "How many employees do you have? ";
cin >> employees;
cout << endl;



for (int a = 0; a < employees; a++)
{

cout << "Enter your first name: ";
cin >> name;
CS[a].setFirstName(name);

cout << "Enter your last name: ";
cin >> name;
CS[a].setLastName(name);

cout << "Enter your hours worked: ";
cin >> number;
CS[a].setHours(number);

cout << "Enter your hourly wage: ";
cin >> number;
CS[a].setWage(number);

CS[a].setPay();


}


for (int a = 0; a < employees; a++)
{

cout << "First Name: " << CS[a].getFirstName() << endl;
cout << "Last Name: " << CS[a].getLastName() << endl;
cout << "Hours Worked: " << CS[a].getHoursWorked() << endl;
cout << "Hourly Wage $: " << CS[a].getWage() << endl;
cout << "Gross Pay $: " << CS[a].getGrossPay() << endl;
cout << "Tax $: " << CS[a].getTax() << endl;
cout << "Net Pay $: " << CS[a].getNetPay() << endl;

}

cin.get();
exit(0);
}
Remove all the [X] from the members of employee. Within the class you don't have arrays. The array is this employee CS[X];.

Further more: You cannot use X as an index because the index within the array starts with 0 and hence ends at X - 1. So because X is out of bounds you get the crash.

I suggest that you use a more descriptive name instead of X like max_employees or so.
Thank you so much, it works absolutely perfect now!
Topic archived. No new replies allowed.