We an access the private member variables of the class without friend function and member function of the class.
#include <iostream>
#include <string>
using namespace std;
class ABC
{ private:
int a,b;
public:
void show() {
cout<<"a="<<a<<" and b="<<b; }
};
int main()
{
ABC obj;
int *p_obj=(int*)&obj; //p_obj is neither member function nor the friend function of the class ABC.
*p_obj=10; // It will set the value of a to 10.
*(p_obj+1) = 20; //It will set the value of b to 20.
obj.show();
}
Output:
a=10 and b=20
In the above example the pointer variable p_obj can access the private member variables a,b of the class ABC.
*(p_obj+1) -- It points to the next variable defined in the class. Here it points to b.
*(p_obj+n) -- By increasing the value of n we get going to access the next to next variables of the class.
p_obj will always having the base address of the class object obj.
Please let me know your comments below and correct me if you find any mistake.
#include <iostream>
#include <string>
using namespace std;
class ABC
{ private:
int a,b;
public:
void show() {
cout<<"a="<<a<<" and b="<<b; }
};
int main()
{
ABC obj;
int *p_obj=(int*)&obj; //p_obj is neither member function nor the friend function of the class ABC.
*p_obj=10; // It will set the value of a to 10.
*(p_obj+1) = 20; //It will set the value of b to 20.
obj.show();
}
Output:
a=10 and b=20
In the above example the pointer variable p_obj can access the private member variables a,b of the class ABC.
*(p_obj+1) -- It points to the next variable defined in the class. Here it points to b.
*(p_obj+n) -- By increasing the value of n we get going to access the next to next variables of the class.
p_obj will always having the base address of the class object obj.
Please let me know your comments below and correct me if you find any mistake.