Prog - Private Members in Java/C++

Well as we all know private members of a class cannot be accessed directly by objects. We need to use member functions to access them. This is true for all cases. Or so I thought until I encountered few cases where this ain't true.

For the first, one thing has to be understood. Memory for the member variables are arranged in a sequential manner. So by performing arithmetic calculations on the address of the public variables we can get the address of the private members and hence access them.

Second. I found this when i was looking at copy constructors. A sample copy constructor would look something like this.

class sample
{
private : int i,j;
public:
sample(sample A)
{
i=A.i;
j=A.j;
}
...
...
};

Here the object A seems to access it s private members without calling any of it's own member functions(the constructor it is present is not called by that object). Now look at the following code.

class sample
{
private: int i,j;
public:
void well( )
{
sample test;
test.i = 5; //test accessing it s private members without
test.j = 10; // use of any objects
}
...
...
}

So the point is an object created inside a member function of the same class can access the private members directly. Note that the member function should be from the same class. For eg if the well( ) func had been in another class it would show error that object trying to access private members.

There is of course another, much simpler way of accessing these private members. By simply changing the "private" keyword to "public" keyword :)

Note : The above logics are applicable in both C++ and Java.

No comments: