Need help with Constructor

Class:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Student
{
	private:
		string name;
		int id;
		int *test;
		int num;
		void makeArray();
	public:
		Student();
		Student(int n);
		Student(string nm, int i, int n);
		void setName(string nm);
		void setID(int i);
		void setScore(int i, int s);
		string getName() const;
		int getID() const;
		void showScore();
		void display();
		~Student();			
};


Constructor:
1
2
3
4
5
6
7
8
9
void Student::makeArray()
{
	int size = Student::num;
	int *studentArray;
	studentArray = new int[num];
	Student::test = studentArray;

	test = 0;
}


I have spent the last few hours getting it down to the error in my code being something to do with the constructor. The constructor should dynamically allocate an int array with num elements, assigns the address of the array to
test, and assigns 0 to all the elements.

i need help very badly. PLEASE HELP ME!!!
Last edited on
test = 0; does not assign 0 to all elements. It assigns 0 to test, effectively whiping out the address of the array that was put in there. You need to use a for loop. Something like this:
1
2
for (int i = 0; i < size; i++)
    test[i] = 0;
So now i have the constructor looking like
1
2
3
4
5
6
7
8
9
10
void Student::makeArray()
{
	int size = Student::num;
	int *studentArray;
	studentArray = new int[num];
	Student::test = studentArray;

	for (int i = 0; i < size; i++)
		test[i] = 0;
}


should that work, or was i suppose to put the loop somewhere else?

because i am still getting the same error as before :(

would it be helpful if i posted my whole code?
Last edited on
closed account (D80DSL3A)
That is not the constructor. That is some other function.
Are you calling makeArray() from the constructor?


What is the actual error you are getting?

Also, a lot of that mumbo-jumbo with the local variables in makeArray() could be eliminated:
1
2
3
4
5
6
void Student::makeArray()
{
	test = new int[num];
	for (int i = 0; i < num; i++)
		test[i] = 0;
}
I figured it out, thanks for the help guys it had to do with the ACTUAL contructor, thought makeArray was the constructor but i needed to call makeArray in the constructor.

Thanks for the help :D
Topic archived. No new replies allowed.