Inside main.cpp
class vivek
{
int i;
float d;
public:
vivek()
{
i = 4;
d = 4.44;
}
~vivek()
{
cout << "destructor" << i;
}
int get()
{
return i;
}
};
int main()
{
vivek *viku = new vivek;
vivek *p;
p = viku;
cout << (*(int*) (p));
getchar();
return 0;
}
Through above code i can able to access variable i , but i want to know how can i access the variable d .
I know this concept shall not be advisable since it violates encapsulation .. But i just want to know how we can do this ?
While it’s extremely hacky, it is possible, because
vivekis a standard-layout struct. This means you can do this:This relies on [class] points 7 and 8 (definition of standard-layout struct) and on [class.mem] points 17 and 20 (layout-compatibility of standard-layout structs).
Disclaimer I am in no way advocating this as a reasonable thing to do. I am just saying that it is actually possible.