IMHO, the existing answers give a bad job explaining the "Why" of this - too much attention, repeating what kind of behavior really is. "Access modifiers work at the class level, not at the object level." - yes, but why?
The general concept here is that the programmer (s) designs, writes, and maintains a class that (as expected) understands the desired OO encapsulation and is authorized to coordinate its implementation. So, if you write class X , you code not only how a single object X x can be used by code with access to it, but also like:
- derived classes can interact with it (via optionally pure virtual functions and / or secure access) and
- Various
X objects collaborate to provide the intended behavior, observing the applied conditions and invariants from your design.
This is not just a copy constructor - a large number of operations can include two or more instances of your class: if you compare, add / multiply / divide, copy, clone, assign, etc., this is often the case when you either just have to have access to private and / or protected data in another object, or you want it to allow faster or faster implementation of a function.
In particular, these operations can use privileged access to do things like:
- (copy constructors) use the private member of the "rhs" object (right side) in the initialization list, so the member variable itself is built by copying instead of the default one (if it is even legal), and then assigned too (again, if it legally)
- share resources - files, shared memory segments,
shared_ptr to reference data, etc. - take responsibility for things, for example.
auto_ptr<> "moves" ownership of an object under development. - copy private "cached", calibration or government items necessary to create a new facility in an optimally used state without having to regenerate them from scratch
- copy / access information / trace information stored in the copied object, which is not otherwise accessible through the public APIs, but can be used by some later exception object or logging (for example, something about the time / circumstances when the "original "copy built instance)
- make a more efficient copy of some data: for example, objects can have, for example, a
unordered_map , but publicly set begin() and end() iterators - with direct access to size() you could reserve capacity for faster copying; worse if they only set at() and insert() and otherwise throw .... - copy links back to parent / coordination / control objects that may be unknown or write-only for client code.
Tony Delroy Jul 18 '13 at 10:40 2013-07-18 10:40
source share