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)
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With