Why can I access private variables in the copy constructor?

C++PrivateAccess Specifier

C++ Problem Overview


I have learned that I can never access a private variable, only with a get-function in the class. But then why can I access it in the copy constructor?

Example:

Field::Field(const Field& f)
{
  pFirst = new T[f.capacity()];

  pLast = pFirst + (f.pLast - f.pFirst);
  pEnd  = pFirst + (f.pEnd - f.pFirst);
  std::copy(f.pFirst, f.pLast, pFirst);
}

My declaration:

private:
  T *pFirst,*pLast,*pEnd;

C++ Solutions


Solution 1 - C++

The access modifiers work on class level, and not on object level.

That is, two objects of the same class can access each others private data.

Why:

Primarily due to efficiency. It would be a non-negligible runtime overhead to check if this == other each time you access other.x which you would have to if the access modifiers worked on object level.

It's also kind of semantically logical if you think of it in terms of scoping: "How big part of the code do I need to keep in mind when modifying a private variable?" – You need to keep the code of the whole class in mind, and this is orthogonal to which objects exist in runtime.

And it's incredibly convenient when writing copy constructors and assignment operators.

Solution 2 - C++

IMHO, existing answers do a poor job explaining the "Why" of this - focusing too much on reiterating what behaviour's valid. "access modifiers work on class level, and not on object level." - yes, but why?

The overarching concept here is that it's the programmer(s) designing, writing and maintaining a class who is(are) expected to understand the OO encapsulation desired and empowered to coordinate its implementation. So, if you're writing class X, you're encoding not just how an individual X x object can be used by code with access to it, but also how:

  • derived classes are able to interact with it (through optionally-pure virtual functions and/or protected access), and
  • distinct X objects cooperate to provide intended behaviours while honouring the post-conditions and invariants from your design.

It's not just the copy constructor either - a great many operations can involve two or more instances of your class: if you're comparing, adding/multiplying/dividing, copy-constructing, cloning, assigning etc. then it's often the case that you either simply must have access to private and/or protected data in the other object, or want it to allow a simpler, faster or generally better function implementation.

Specifically, these operations may want to take advantage of priviledged access to do things like:

  • (copy constructors) use a private member of the "rhs" (right hand side) object in an initialiser list, so that a member variable is itself copy-constructed instead of default-constructed (if even legal) then assigned too (again, if legal)
  • share resources - file handles, shared memory segments, shared_ptrs to reference data etc.
  • take ownership of things, e.g. auto_ptr<> "moves" ownership to the object under construction
  • copy private "cache", calibration, or state members needed to construct the new object in an optimally usable state without having to regenerate them from scratch
  • copy/access diagnostic/trace information kept in the object being copied that's not otherwise accessible through public APIs but might be used by some later exception object or logging (e.g. something about the time/circumstances when the "original" non-copy-constructed instance was constructed)
  • perform a more efficient copy of some data: e.g. objects may have e.g. an unordered_map member but publicly only expose begin() and end() iterators - with direct access to size() you could reserve capacity for faster copying; worse still if they only expose at() and insert() and otherwise throw....
  • copy references back to parent/coordination/management objects that might be unknown or write-only for the client code

Solution 3 - C++

You can access private members of a class from within the class, even those of another instance.

Solution 4 - C++

To understand the answer, I would like to remind you few concepts.

  1. No matter how many objects you create, there is only one copy of one function in memory for that class. It means functions are created only once. However variables are separate for each instance of the class.
  2. this pointer is passed to every function when called.

Now it's because of the this pointer, function is able to locate variables of that particular instance. no matter if it is private of public. it can be accessed inside that function. Now if we pass a pointer to another object of the same class. using this second pointer we will be able to access private members.

Hope this answers your question.

Solution 5 - C++

Copy constructor is class' member function and as such has access to class' data members, even those declared as 'private'.

Solution 6 - C++

why the man who made that compiler allow this behavior, that we can see hidden members of an object (that its type is the same of the class where you access the hidden members) in copy constructor or in any method in the class.

The answer: because you when you are in the class that's mean you are the builder or the designer of the class also mean that you know all data members and methods in that class that's why he allow this behavior because you build this class you know every thing about it unlike the users of the class they haven't to know every thing about the class like you.

the idea of hiding data members or method that help the users of this class and not confused them with non important things.

That's it.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiondemonkingView Question on Stackoverflow
Solution 1 - C++aioobeView Answer on Stackoverflow
Solution 2 - C++Tony DelroyView Answer on Stackoverflow
Solution 3 - C++Alexander RaffertyView Answer on Stackoverflow
Solution 4 - C++Ali ZaibView Answer on Stackoverflow
Solution 5 - C++Bojan KomazecView Answer on Stackoverflow
Solution 6 - C++mahmoud bashaView Answer on Stackoverflow