I get 2 errors and I don't know why I can't make int courses(NumCourses);
I get these errors:
'Student::NumCourses' : is not a type name
'NumCourses' : undeclared identifier
When I do what you suggested above, I still get these errors:
1>c:\users\jas\documents\visual studio 2010\projects\project 3\project 3\Student.h(19): error C2327: 'Student::NumCourses' : is not a type name, static, or enumerator
1>c:\users\jas\documents\visual studio 2010\projects\project 3\project 3\Student.h(19): error C2065: 'NumCourses' : undeclared identifier
1>c:\users\jas\documents\visual studio 2010\projects\project 3\project 3\Student.h(19): error C2864: 'Student::courses' : only static const integral data members can be initialized within a class
Ok, thanks it works now. :)
But would you mind explaining why I couldn't do that? I am fairly new to C++ and just want to know the details so I won't make the same mistake again.
The trick is that int* courses= newint[NumCourses]; is not something that should be done in the class itself. It should be defined in the class, but allocated in the constructor.
#include <iostream>
#include <string>
usingnamespace std;
class Student
{
public:
int NumCourses;
Student(string studentname, int studentcourses)
{
name = studentname;
NumCourses = studentcourses;
courses = newint[NumCourses]; // Allocation done in the contructor
}
~Student()
{
delete[] courses; // Remember to delete the memory in the destructor or you'll have a memory leak
}
string name;
int* courses; // here it is defined
double cGPA, dGPA, pGPA;
};
You're welcome, I was still writing while you guys were sorting it out.
The reason why you couldn't do it the other way before was that the size of courses[] is determined at compile time, not runtime. Therefore the compiler needs to know how much memory to save for this object. If you declare an array with a non-constant, then it means that you can change the size of the array at runtime. It is possible to do this with dynamic memory (which is what we introduced you to) because memory is taken from the "heap", but it is not possible to do this the conventional method because the memory is put into the "stack" whose size cannot be changed mid-function.