Feeds:
Posts
Comments

Archive for November, 2004

I came across a big surprise yesterday. I was reading a book on C++ (Stanley Lippman‘s C++ Primer) and came across the fact that (in C++) objects made from the same class can access each other’s private members. I kinda felt ashamed that I didnt know this fact till now. I was much surprised also, since it seemed quite counter-intuitive. But I am not a person who would argue with Stanley Lippman ;-), so I accepted it in its face value. I decided to try it out later on my system.
Today I tried it out and verfied the correctness. Excited by this “new discovery” I told this fact to 3 people who has more than 5 years of experience in jave and they all said that this was not the way things are in java, and that in java you couldnt access the private member variable of another object, regardless of whether the objects belong to same class or not.
But I didnt take their statement in the same way as I did with Lipppman, I immediately tried it out and foung that they were wrong 🙂 An object can access the private member of another object of same class. None of them could take that in so easily. I showed them the code, compiled and executed it. They were convinced.
I found out that the access specifiers are for a class and not for individual objects. Anf if you think about it, there is actually no problem with this implementation. If an object has to access private members of another object of same class, the class author would know exactly how the interactions take place and what the implications of the interaction are.
Well, I am still surprised 🙂

The programs that i tried out in C++ and java are given below :

//==================================================================================
//C++ Example
//private_mem.cpp
//==================================================================================


#include

using namespace std;

class A
{
private:
int m_a;

public:
A(int a);
int func(A& a_object);
};

A::A(int a)
{
m_a=a;
};

int A::func(A& a_object)
{
//access member variable of another object
return a_object.m_a;
};

int main()
{
A a(10);
A b(20);
a.func(b);
return 0;
}

//==================================================================================
//Java Example
//myClass.java
//==================================================================================

class testClass
{
private int x;

public void print(testClass testObject)
{
//access member variable of another object
System.out.println(testObject.x);
}
}


class myClass
{
public static void main(String args[])
{
testClass a = new testClass();
testClass b = new testClass();
a.print(b);
}
}

Advertisements

Read Full Post »

You Too…

U2’s new album : How To Dismantle An Atomic Bomb is the top selling music album at Amazon. U2 already has 14 Grammies to their credit. Will their new album bring more ?

Read Full Post »