I do not understand the two lines mentioned below in the code that I have provided here. Why I need to use int*
? How I am accessing the private variable? I am not sure what I am doing with these two lines. Please explain in detail.
Problematic lines:
int *p = (int *) &s;
*p=10;
Main Code:
#include <iostream>
using namespace std;
class sample {
private:
int a;
public:
void function () {
a=5;
}
void printA () {
cout<<"value is "<<a<<endl;
}
};
int main () {
sample s;
s.function();
s.printA();
int *p = (int *) &s;
*p=10;
s.printA();
}
Using (int*)
there is a really really bad idea. You are using a class, that isn't an int, as an int. Which is bad.
You can't access private members, and you shouldn't, that's why they are private.
int *p = (int *) &s;
*p=10;
This means, you have an object s
, of type sample
, and it has a data member int a;
. What you wrote works, because a
happens to be at the beginning of the class.
There are some cases where the layout of a class is guaranteed, you can read about it here: