Monday, November 19, 2007

Accessing a class variable inside another class

I thought that the only means to access a class
variable inside another class is by inheriting
or through the use of friend functions.

Another approach is by creating the internal
variable of a class as a pointer, and passing
the pointer to another class to provide full
access to the variable.

Here is a code snipet that shows how it works:

class A{

int *a;
public:
void print(int *t)
{
printf("\nValue from another class: %d", *t);
printf("\nValue from this class : %d", *a);
}
A()
{
*a = 2;
}

};

class B{

int *b;
public:
B()
{
*b = 5;
}
int *getB(void)
{
return b;
}

};

int main()
{
int *temp;
A objA;
B objB;
temp = objB.getB();
objA.print(temp);
}


Result of a run shows:
Value from another class: 5
Value from this class : 2