c++ - Why the dangling pointer is giving the size of the previously pointed variable? -
this question has answer here:
class b { public: b():a(0), b(0) { } b(int x):a(x), b(0) { } private: int a; int b; }; class { public: a(b* ptr):pb(ptr) { } void modifypb() { delete pb; pb = null; } void printbsize() { if( pb != null ) cout<<"pb pointing obj size:"<<sizeof(*pb)<<endl; else cout<<"pb pointing obj size:"<<sizeof(*pb)<<endl; } private: b *pb; }; void main() { b *bobj = new b(10); cout<<"size of bobj:"<<sizeof(*bobj)<<endl; aobj(bobj); cout<<"size of aobj:"<<sizeof(aobj)<<endl; cout<<"before de-allocating: "; aobj.printbsize(); aobj.modifypb(); cout<<"after de-allocating: "; aobj.printbsize(); } output:
size of bobj: 8 size of aobj: 4 before de-allocating: pb pointing obj size: 8 after de-allocating: pb pointing obj size: 8 why size of *pb 8, after de-allocation ?
why size of *pb 8, after de-allocation ?
sizeof(*pb) evaluated @ compile time based on type of *pb. value not depend on value of pb @ run time.
you printing sizeof(b) in both branches of if statement, 8 on platform.
Comments
Post a Comment