Both private and public member variables reside in consecutive memory locations, so using pointer to member variable we can access private values even outside the class.
Take a look:
#include<iostream.h>
class A
{
public :
int x;
A()
{
cout<<"Enter a b c:";
cin>>a>>b>>c;
}
private:
int a,b;
char c;
};
int main()
{
A ob,*p;
p=&ob;
int *y=&(p->x); // y stores address of public member x
cout<<"\nInside main:\n";
cout<<"a="<<*++y;
cout<<"b="<<*++y;
cout<<"c="<<(char)*++y;
return 0;
}
class A
{
public :
int x;
A()
{
cout<<"Enter a b c:";
cin>>a>>b>>c;
}
private:
int a,b;
char c;
};
int main()
{
A ob,*p;
p=&ob;
int *y=&(p->x); // y stores address of public member x
cout<<"\nInside main:\n";
cout<<"a="<<*++y;
cout<<"b="<<*++y;
cout<<"c="<<(char)*++y;
return 0;
}