8

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)

Gabriel Schreiber
  • 2,166
  • 1
  • 20
  • 33

3 Answers3

13

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.

sharptooth
  • 167,383
  • 100
  • 513
  • 979
8

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
Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625
2

You can use CRTP idiom, if possible, as I described here: https://stackoverflow.com/a/14730166/908336

Community
  • 1
  • 1
Masood Khaari
  • 2,911
  • 2
  • 23
  • 40