i have a custom class, let's call it "Student" and a main method. I'm instanciating the class, and just want to output the content of the class.
My programm crashes with a: Process finished with exit code 139 (interrupted by signal 11: SIGSEGV)
Actual Code
Student.h
#ifndef PROG2_STUDENT_H
#define PROG2_STUDENT_H
#include <iostream>
class Student
{
private:
char *name;
char *firstName;
unsigned matriculationNumber;
unsigned semester;
public:
Student(char *name, char *firstName, unsigned matriculationNumber, unsigned semester);
~Student();
friend std::ostream &operator<<(std::ostream &ostream, const Student &student);
private:
};
#endif
Student.cpp
#include <cstring>
#include "Student.h"
Student::Student(char *name, char *firstName, unsigned matriculationNumber, unsigned semester)
{
std::strcpy(this->name, name);
std::strcpy(this->firstName, firstName);
this->matriculationNumber = matriculationNumber;
this->semester = semester;
}
Student::~Student()
{
delete[] this->name;
delete[] this->firstName;
}
std::ostream &operator<<(std::ostream &stream, const Student &input)
{
stream << input.name << ", " << input.firstName << ": "
<< input.semester << " Semester, MA " << input.matriculationNumber;
return stream;
}
and my main
#include <iostream>
#include "StudentPackage/Collection/StudentCollection.h"
int main()
{
Student studentOne((char *)"Testerson", (char *)"Test", 12345, 2);
std::cout << studentOne << std::endl;
return 0;
}
What i have tried
I have tried several things, including memcpy. But with memcpy I'm not able to detect the size of the char array correctly.
When i change the Student Constructor to the following, i get problems with the delete/free in the destructor. I guess, this isn't the correct way anyway, but this is happening, because the scope of the input variables are destroyed before the class destructor is called, correct?
Student::Student(char *name, char *firstName, unsigned matriculationNumber, unsigned semester)
{
this->name = name;
this->firstName = firstName;
this->matriculationNumber = matriculationNumber;
this->semester = semester;
}
Question
- How can i correctly copy the char array from constructor (name to this->name)?
- How can i correctly copy the char array from constructor (firstName to this->firstName)?