Yousaf Yousaf - 11 days ago 4
C++ Question

Making a dynamic array of objects and Initializing it

i have two classes that are Student and StudentArray.

In class Student, i have declared some student's attributes like name, ID, age etc.

In StudentArray class, i want to create an array of Student type. StudentArray class also contains some functions like Insert that will insert data in the Student type array. I want to add complete student's data like name,age,id etc of one student at the same index of the Array but i can't understand how to do that.

I also can't understand how to initialize the array in the constructor of StudentArray class. This is what i have done so far.

Student Class

class student
{
public:
string name;
int id;
int age;
string semester;
string degreeprogram;
};


StudentArray Class

class StudentArray
{
public:
student *s;
int used;

StudentArray();
~StudentArray();
void input();
void Insert(string n,int i,int a, string s, string dp);
int Search(string n, int i);
void DeleteAnyStudent(string n, int i);
void DeleteAll();
void Edit(string n, int i);
void show();
};


Constructor of StudentArray class

StudentArray::StudentArray()
{
s = new student[100];
for(int i=0;i<100;i++)
{
s[i] = new student(); //ERROR HERE
}
used = 0;
}


Insert Function in StudentArray class

void StudentArray::Insert(string n,int i,int a, string s, string dp)
{
s[used].name = n; //ERROR HERE
s[used].id = i; //ERROR HERE
s[used].age = a; //ERROR HERE
s[used].semester = s; //ERROR HERE
s[used].degreeprogram = dp; //ERROR HERE
used++;
}


i am using code blocks.

In the constructor of StudentArray, error message is
"no match for operator 'operator=' (operand types are ;student' and 'student*' )". In the insert function, the error message is "error: request for member 'id' in 's.std::basic_string<_CharT, _Traits, _Alloc>::operator[]<char, std::char_traits<char>, std::allocator<char> >(((std::basic_string<char>::size_type)((StudentArray*)this)‌​->StudentArray::used‌​))', which is of non-class type 'char'|"


In the insert function, same error is thrown at every line after which i have written "ERROR HERE", only the name of the variable like name, id or age etc changes

Answer

After s = new Student[100]; you have an array of 100 default initialised Student objects, which I think is exactly what you want.

But you then try to assign to each one a pointer to another, newly allocated object. That can't work - you're trying to assign a pointer to an object - and isn't needed anyway. If you just delete that loop entirely you'll be better off.

EDIT: Your second problem is because you have a parameter named s which is a string. That hides your member variable called s. You need to rename one of them. (It shouldn't be hard to find a better name!)

Comments