user3091585
user3091585

Reputation: 41

How do you use strings in a class?

Well I've been working on this for awhile but I can't seem to figure it out.

#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
#include "student.h"

using namespace std;

int numofstudents = 5;
Student ** StudentList = new Student*[numofstudents];
string tempLname = "smith";
StudentList[0]->SetLname(tempLname);


#include<iostream>
#include <string>

using namespace std;

class Student {

public:
  void SetLname(string lname);
  void returnstuff();

protected:
  string Lname;

};

#include <iostream>
#include "student.h"
#include <iomanip>
#include <cctype>
#include <cstring>
#include <string>

using namespace std;

void Student::SetLname(string lname) {
  Lname = lname;
}

All I want to do is set Lname to smith but when I run my program it crashes without telling me an error after it runs. Any help would be greatly appreciated!

Upvotes: 0

Views: 62

Answers (3)

Sergey Prokhorov
Sergey Prokhorov

Reputation: 135

You created array of pointers to Student but the elements of array were not initialized, so dereference of any element, in particular [0] leads to crash. Use "std::vector StudentList(numofstudents);" instead with minor changes in code "StudentList[0].SetLname(tempLname);"

Upvotes: 0

Benjamin Lindley
Benjamin Lindley

Reputation: 103703

Your problem is nothing to do with using strings. It is to do with using pointers.

Student ** StudentList=new Student*[numofstudents];

This allocates an array of Student pointers. It does not allocate an array of Student objects. So, as of this line of code, you have an array of 5 invalid pointers. Which is a problem when you try to access them as if they point to Student objects, here:

StudentList[0]->SetLname(tempLname);

In order for that line to be valid, StudentList[0] first needs to point to a valid Student object. You can either Set it to an existing object:

Student st;
StudentList[0] = &st;

Or you can allocate a new object:

StudentList[0] = new Student;

Otherwise get rid of the extra level of indirection:

Student * StudentList=new Student[numofstudents];
...
StudentList[0].SetLname(tempLname);

But why on Earth would you do that? If you need a 1-dimensional dynamic collection of Student objects, then use a sequence container from the standard library, such as a std::vector.

Upvotes: 2

BlackMamba
BlackMamba

Reputation: 10254

change Student ** StudentList=new Student*[numofstudents]; to

Student ** StudentList=new Student*[numofstudents];
for(int i = 0; i<numofstudents; i++)
    StudentList[i] = new Student();

Upvotes: 0

Related Questions