So my goal is to create many objects of the same class without copying one object many times. I think i found a way by making an array of pointers that point to a certain object but i get a segmentation fault.
Unfortunately in this project I'm trying to do, I'm not using any other libraries except <cstring>
(I have to add here that the constructor of the class has some parameters as input).
Thoughts?
Here is the code:
#include <iostream>
#include <cstring>
using namespace std;
int main(void)
{
int i, floor, classroom; //the floor of the school and the classroom the student is heading to
char *stname;
typedef Student *stptr;
stptr *students = new stptr[15];
for (i = 0; i < 15; i++)
{
cin >> stname;
cin >> floor;
cin >> classroom;
students[i] = new Student(stname, floor, classroom);
}
}
...and the code for the class:
class Student
{
private:
char *name;
int no_floor;
int no_classroom;
public:
Student(const char *nam, int no_fl, int no_cla) //constructor
{
name = new char[strlen(nam + 1)];
strcpy(name, nam);
no_floor = no_fl;
no_classroom = no_cla;
cout << "A new student has been created! with name " << name << " heading to floor: " << no_floor << " class: " << no_classroom << endl;
};
~Student() //destructor
{
cout << "A Student to be destroyed! with name " << name << " is at floor: " << no_floor << " class: " << no_classroom;
delete[] name;
};
};