Search code examples
c++class-designencapsulation

Class design with vector as a private/public member?


what is the best way to put a container class or a some other class inside a class as private or a public member?

Requirements:

1.Vector< someclass> inside my class

2.Add and count of vector is needed interface


Solution

  • If the container's state is part of the class's invariant, then it should, if possible, be private.

    For example, if the container represents a three dimensional vector then part of the invariant might be that it always contains exactly 3 numbers. Exposing it as a public member would allow code external to the class to change the containers size, which in turn could cause problems for any routine which requires the container's size to be constant. Keeping the container private limits the places in your software where the container's size can be modified to the class's member functions.