Classes and arrays

Jul 25, 2018 at 7:29pm
Hi. I am trying to write a database on c++ to practice classes. I've created a class called PersonalData and the name is Person. Now, since the program is connected to a .txt file, which I want to be able to access directly from the program, the number of people in database will vary and therefore I want Person to be an array but it gives me an error: Invalid use of nonstatic data member. What on earth have I done?
here's a piece of code with the error.
class PersonalData
private:
int PeopleinDatabase;
PersonalData Person[PeopleinDatabase]; //ERROR HERE
short index;
string name;
short age;
public:
void AddPerson();
void ShowPeople();
void Loadpeople();
void DeletePerson();
void SaveToFile();
void SearchForPeople();
PersonalData ();
~PersonalData();


I apologise for the messy question, I'm pretty new to programming and this forum.
Thanks!
Jul 25, 2018 at 7:34pm
Do you realize that in C++ array sizes must be compile time constants?

Instead of the array you should consider std::vector instead.

Jul 25, 2018 at 7:36pm
standard c++ does not allow a variable for array size because it is supposed to be allocated at compile-time to a fixed size.

the standard container vector is what you need. (it isnt really a vector, it is misnamed, its an array themed container class).
#include <vector>

vector <Person> P(optional_known_size_is_good_to_put_here);
P[0].method(); //etc acccesses like array

if you don't know its max size, you can grow it with push_back (adds 1 more to the end each time used).

P.size() is useful as well (current size).
Last edited on Jul 25, 2018 at 7:37pm
Topic archived. No new replies allowed.