Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find out the size of a polymorphic object

I have an pointer Base* base_ptr to an polymorphic object. Is it possible to find out the size of the dynamic type of said object?

AFAIK, sizeof(*base_ptr) yilds the size of the static type of base_ptr. I'm beginning to suspect this isn't possible, but maybe I'm overlooking something.

Note: I'm aware that I could add a virtual function to my type hierarchy which returns the size, but this is not a desirable solution in my case.

EDIT: sizeof(base_ptr) -> sizeof(*base_ptr)

like image 692
Gabriel Schreiber Avatar asked Nov 14 '11 14:11

Gabriel Schreiber


2 Answers

No, you can't do that in C++ - at least in a portable way. The best bet would be to have getSize() member function implemented in each class.

like image 175
sharptooth Avatar answered Sep 20 '22 00:09

sharptooth


Yes. You can implement a virtual function in the base class which returns the size:

class Base
{
   virtual int size() { return sizeof(Base); }
};
class Derived : public Base
{
   virtual int size() { return sizeof(Derived); }
};

//......
Base* b = new Derived;
int size = b->size(); //will call Derived::size() and return correct size
like image 34
Luchian Grigore Avatar answered Sep 20 '22 00:09

Luchian Grigore