How can I access a series of object from an object? - resolved

I've made a really simple example situation below (code not finished, need your help for that) to show what I mean. I used the teacher and student example to make it easy to understand what I want to do.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
// marks.cpp
#include <iostream>
using namespace std;

// compile and run:		clear && g++ -Wall marks.cpp && ./a.out

class Teacher {
private:
	int average_grade;
public:
	Teacher() { average_grade = 0; }	// set to '0' so wont pull up garbage
	void calculate_average ()
	{
		/* Would like to get all Students grades in here so the teacher
		 * can calculate the overall average. */
		
		
		cout << "The average grade is: " << average_grade << "%" << endl; 
	}
};


class Student {
private:
	int student_grade;
public:
	void set_grade(int grade) { student_grade = grade; }
	int get_grade() { return student_grade; }
};

int main () {
	
	Teacher MrB;		// create teacher
	Student Pupil[4];	// create an array of 4 student objects
	
	Pupil[0].set_grade(60);		// set students grades
	Pupil[1].set_grade(70);
	Pupil[2].set_grade(80);
	Pupil[3].set_grade(90);
	
	MrB.calculate_average();	// teacher will calculate grades
	
	return 0;
}



I understand that I could easily do a for-loop in main to get the averages but I don't want to do that. I want to be able to have another class open all 4 student objects at one time and make the calculation so that main can be kept clean. It's been days and I've read into inheritence, polymorphism, and friend class information and none of those seem to be the solution. It seems I need some sort of pointer implimentation to bring the students objects into the teacher object but I'm unsure how to do that.

Any help would be greatly appreciated.
Last edited on
ne555,

I see the image but i'm having trouble interperting it. Would you mind explaining this to me?
You need to create relationships between your objects to operate with them.

There is a relationship between a course and a student. One of the properties of the relationship is the `grade'.
The idea is to traverse the list of grades and average them. `Teacher' may set the grade, but it does not participate in the computation.

A possible implementation
1
2
3
4
5
6
7
8
9
10
11
12
struct grade{
   course *the_course;
   student *the_pupil;
   int score;
};

class course{
   std::vector<grade> the_grades;
public:
   int average_grade() const;
//...
};
In order to create the relationship between a particular student and course, you need to enrol it.course["oop"].enrol( a_student );
ne555,

thats not quite what i was looking for but after more searching on the web i found the answer:

http://www.daniweb.com/software-development/cpp/threads/37550/passing-arrays-of-objects-to-member-functions
Topic archived. No new replies allowed.