Search code examples
c++pointersencapsulation

encapsulation and pointers to objects


class CommandSchedule
    {
    private : 
       List<SubSchedule*> mSubScheduleList;
    public  :  
       void addSubSchedule (int id) 
       {  
          mSubScheduleList.add(new SubSchedule(id));
       }
       SubSchedule* addSubSchedule (int id) 
       {
          SubSchedule* item = new SubSchedule(id);

          mSubScheduleList.add(item);

          return item;
       }
    };

In this class, I define 2 addSubSchedule functions one returning void, one returning pointer to the object.

So, my question is that, if the function, which returning pointer to the object, breaks the encapsulation of CommandSchedule class ? I feel uncomfortable with encapsulation issue, so any help is appreciated a lot.


Solution

  • Why would it break encapsulation? The internal representation of your objects is still hidden:

    private : 
       List<SubSchedule*> mSubScheduleList;
    

    Unless SubSchedule is also considered internal representation, there's no problem here.

    In a well-encapsulated class only its member functions can manipulate its internal details. In this case, the fact that a List is used seems to be a detail, because all that an user of the public interface cares about is that the class lets him add subschedules. How those subschedules are stored is an internal detail. You could later change this detail (say, storing them in a SortedList instead) without affecting the users of the public interface. So, making the List<...> variable private promotes good encapsulation.

    If the user of the interface expects to be able to manipulate SubSchedule objects directly, then there's no problem in exposing that. But if there's no reason to do that, then the use of SubSchedules is probably an internal detail as well, and as such should not be exposed in the public interface.