Saturday, July 24, 2004

Re: OOP's basics - Access

Revo, I'm not really sure what you are asking here. Are you asking how Access Control is implemented in C++ / Java? or what is Access Control?

I'll answer the second question here. Consider the following code :



#include "iostream" //replace the double quotes by < >
using namespace std;

class base
{
public:
int bval;
base(){ bval=0;}
};

class deri : public base //Note : Here it is public
{
public:
int dval;
deri(){ dval=1;}
};

class deri2 : public deri
{
public:
int dval2;
deri2(){ dval2 = 2; }
};

int main()
{
deri d1;
deri2 d2;

/* The following code is Legal when "base" is public to "deri"

d1.bval = 9; //bval is accessible because base is now a public part of deri
d2.bval = 10; // same for deri2, cause deri is public to it, which in turn makes base public

*/

/* Now when "base" is protected to "deri", the above code in red is not possible because
of the semantics of the protected key-word, which can be found in any book.
But note here that members of "base" are accessible to "deri2"'s class definition,
It's just that the objects of deri2 can't directly access it. Again all this
just pertains to the semantics of "protected".
For eg: this is legal in this context
deri2() { bval = 2; dval2 = 3; }
*/

/* And when "base" is private to "deri", "deri2" has no access to "base"'s members,
"base" just cannot be seen by "deri2".
*/

system("pause");
return 0;
}
So basically, you can say that Access Control pertains mostly to how the various classes work in Heirarchy of classes. If it's just one base and one derived class, then access control is not of much importance, because as you can see there is no difference then between "private" and "protected", only difference which can be found is between "public" and the other two.

If you are still unclear, keep posting.

Dinesh.

No comments: