Sign in to follow this  
nuclear123

questions on aggregation classes

Recommended Posts

[color="#009933"]www.[b]learncpp[/b].com/[b]cpp[/b]-tutorial/103-[b]aggregation

In the example given they state a department can have a teacher and if a department goes out of scope/deconstructs it doesnt destroy the teacher that was in that department. for example in real life departments at different school change names,get added,and get deleted all the time. Just because a department gets deleted doesn't mean they also fire/delete the teachers. My question is i understand this perfectly fine( or so i think as i just described ) but the problem i see with aggregation compositional classes is the following. Say you have the same example given from the website posted above but instead departments have MULTIPLE teachers.

How are you supposed to deal with teachers that are no longer hired? do you just check the address of the pointer and if it's set to 0 you know you need to remove them from the department?
Also
You will have tons of dynamically allocated teachers. How do you manage all of them will i need to create another class in order to do so? if i had done regular class composition this wouldn't have been a problem correct and only 1 class would be needed? [/b][/color]

Share this post


Link to post
Share on other sites
In standard C++, you would use a [i]smart pointer[/i] to point to the teacher. This ensures that the teacher will be destructed correctly when nothing left refers to it. A common solution might be to have a boost::shared_ptr in the department, or even a std::vector of shared_ptrs (for multiple teachers); then other references could use a boost::weak_ptr which will automatically set itself to NULL when the teacher is no longer referenced. This ensures that you clean up your memory while still allowing you to check if a teacher is in scope/etc.

Of course more complex situations generally will require more complex code solutions. For instance, if you have something besides a department that might "own" a teacher, you'd need a slightly more sophisticated way of handling the smart pointers.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this