Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can I access private variables in the copy constructor?

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; 
like image 210
demonking Avatar asked Nov 07 '10 08:11

demonking


People also ask

How does copy constructor access private variables?

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).

Can constructor access private variables?

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.

Can copy constructor be private?

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().

Can objects access private members in Java?

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).


1 Answers

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.

like image 81
aioobe Avatar answered Oct 21 '22 23:10

aioobe