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;
Private members can be accessed only by the class itself. The parameter is an A, so, logically, the copy constructor of A can access its members. The class can always access all members of all its instances (as long as they're passed as parameters, obviously).
So the private variable cannot been seen and accessed from outside the scope of the constructor. But inside it you can alter it, log it, pass it to a function, reassingn it like you want.
As you can see, in the Derived type, the copy constructor was intentionally made private, because it would be bad API design to give programmers to ability to accidentally try to call the copy constructor manually, rather than using the clever interface provided by clone().
This is perfectly legal. Objects of the same type have access to one another's private members. This is because access restrictions apply at the class or type level (all instances of a class) rather than at the object level (this particular instance of a class).
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With