Access rights confusion

Greetings. I am rather confused about what i can and can't do. I am trying to write a class definition and am deciding on the return type of one of the member functions. Is it possible to have a member function of one class return an object of another class? Like can i use a constructor in a member function of another class? If i do what will happen to the object that i have created within the function once i have exited and returned it?

Hope that makes sense.

Thanks.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Cohort
{public:
	Student find(string s);
 private:
 	 vector <string> names;
 	 vector<vector<int> > marks ( 5, vector<int> ( 5 ) );
};


class Student
{ public:
	Student(string nm, int m1, int m2, int m3);
	string	getname() const { return name; }
	void	display() const;
  private:
	string name;
	int	math, comp, stat;
};


e.g. in the above example will i be able to construct a temporary Student object from the values stored within the vectors in Cohort object and then return it?
Last edited on
Yes, you can return a Student object from Cohort::find. For example:

1
2
3
4
5
6
7
8
9
10
11
12
13
Student Cohort::find()
{
	Student student("billy", 0, 1, 2);
	return student;
}

// ...

int main(int argc, char ** argv)
{
	// ...
	Student student = cohort.find();
}

You create temporary object inside the function and return it. Then, student in main is assigned to copy of the returned object and that temporary is destroyed.

But you have to declare Student before Cohort or define it on another file and #include it.
Ok thanks.
In the example you give do i have to overload the "=" operator?
Topic archived. No new replies allowed.