This topic is now archived and is closed to further replies.


Find size of an object at runtime

Recommended Posts

My problem boils down to finding the size of an object at run-time. See following example. [script] class base { long M }; // Size 4 class derived : public base { long N }; //Size 4 + 4 = 8 int mySizeof( base * argument ); { base * Base = new base(); mySizeof(Base); //returns 4 delete Base; Base = new derived(); mySizeof(Base); //returns 8 delete Base; } [/script] Any ideas about how I can build such a function? Thank you for your time. ToohrVyk ------------- Extatica - a free 3d game engine Available soon! Click here to learn more

Share this post

Link to post
Share on other sites
sizeof won''t work on a pointer to dynamically allocated memory.

The only method I can think of off the top of my head is a bit crap... Use a public method to return the size.

If you''re ok with the size of the vtable being added to the result, you can just do this...

class base

virtual unsigned int size() const { return sizeof(*this); }

you will have to override this in derived classes to get the correct result.

If for some reason you want the size the object would be if it had no virtual functions, you can always return the sum of the sizes of all the members.

There must be a better way than this though...

Share this post

Link to post
Share on other sites