Constant class objects amount?

i have a class called employee and i am trying to create multiple employees from this class based from a text file.
I can add/remove employees from the text file so i do not know how many employees i want to make each time i run the program.

to combat this i have created a variable total_lines and counted the number of lines in the text file.

however when i do:
employee(total_lines)
i get an error which says:
"Expression must have a constant value"

however i do not know the value as it could change each time i run the program.
is there a way to navigate this?
Last edited on
You really need to show more code. We cannot diagnose your problem based on "employee(total_lines)".

If you're trying to create an array somewhere in your code, you can't use a variable as the size. Use a vector instead.

e.g.
1
2
int num_employees = 42; //note: need not be constant value
std::vector<employee> employees(num_employees);


You access a vector in the same way as an array, e.g. vector[0] = employee{...};
https://www.learncpp.com/cpp-tutorial/an-introduction-to-stdvector/
Last edited on
With arrays:

1
2
3
constexpr int MAX_NUM_EMPLOYEES = 100;
Employee employees[MAX_NUM_EMPLOYEES];
int num_employees = 0;  // number of valid employee records in use 

Every time you successfully read an employee, bump the num_employees counter.

I just gave a similar example here (http://cplusplus.com/forum/beginner/283140/#msg1225687), see point #3.

With vectors:

 
#include <vector> 
 
std::vector <Employee> employees;

Use employees.push_back( employee_successfully_read_from_file ) to add employees to your list. The total number of employees is employees.size().

Hope this helps.
thank you!

only question i now have is how would i return these employees back from a function?
You can return a std::vector<Employee> as the return type. Or you can pass a vector by non-const reference.
if you are doing objects, that would get rid of the need to pass the vectors in and out of the functions entirely; the vector becomes a member and the member functions can all see it and change it directly without passing. If this is past where you are in your study, leave it for now but note it in the back of your mind as one of the key advantages of objects (its a lot like having global variables within a limited segment of the code, all the advantages of that idea, without the pain points).
to clarify, you would have another class that will manage the employees
for instance
1
2
3
4
5
6
7
8
9
class human_resources{
public:
   contract(employee e);
   fire(employee e);
   wage_theft();

private:
   std::vector<employee> numbers;
};
Topic archived. No new replies allowed.