questions on aggregation classes

Started by
0 comments, last by ApochPiQ 12 years, 6 months ago
[color="#009933"]www.learncpp.com/cpp-tutorial/103-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?
Advertisement
In standard C++, you would use a smart pointer 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.

Wielder of the Sacred Wands
[Work - ArenaNet] [Epoch Language] [Scribblings]

This topic is closed to new replies.

Advertisement