Tuesday, July 14, 2009

(C++) How can I get the size of an object from a pointer to a base class?

class Class{


public:


int Something;


};





class DerClass : public Class{


public:


int Array[256];


};





main()


{


Class*C = new DerClass;


sizeof(*C); // = 4


sizeof(DerClass); // = 1028


}





// How can I get 1028 from pointer C?

(C++) How can I get the size of an object from a pointer to a base class?
As far as I know, in c++ it is impossible to get the size of an object just from the base class and sizeof function. One way to get around this is to use dynamic_cast as follows.








struct A {


int a;


virtual ~A() {}


};





struct B : public A {


int b[128];


virtual ~B() {}


};





struct C : public A {


int c[256];


virtual ~C() {}


};





size_t sizeofA(A* a) {


if (dynamic_cast%26lt;C*%26gt;(a))


return sizeof(C);


else if (dynamic_cast%26lt;B*%26gt;(a))


return sizeof(B);


else


return sizeof(A);


}
Reply:sizeof() hard codes size of objects into the program at compile time. Allocated (ie: 'new') memory block sizes are unknown until run time, making sizeof() hopeless to help.





So, don't think it can be done via pointer.


No comments:

Post a Comment