Tuesday, 15 July 2014

class - Explanation of typecasting of pointer in C++ -



class - Explanation of typecasting of pointer in C++ -

i not understand 2 lines mentioned below in code have provided here. why need utilize int*? how accessing private variable? not sure doing these 2 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 "<<a<<endl; } }; int main () { sample s; s.function(); s.printa(); int *p = (int *) &s; *p=10; s.printa(); }

using (int*) there really bad idea. using class, isn't int, int. bad.

you can't access private members, , shouldn't, that's why private.

int *p = (int *) &s; *p=10;

this means, have object s, of type sample, , has info fellow member int a;. wrote works, because a happens @ origin of class.

there cases layout of class guaranteed, can read here:

what pod types in c++? what aggregates , pods , how/why special?

c++ class casting private encapsulation

No comments:

Post a Comment