Using the sizeof
operator, I can determine the size of any type – but how can I dynamically determine the size of a polymorphic class at runtime?
For example, I have a pointer to an Animal
, and I want to get the size of the actual object it points to, which will be different if it is a Cat
or a Dog
. Is there a simple way to do this, short of creating a virtual method Animal::size
and overloading it to return the sizeof
of each specific type?
We also know that the class size is defined as the difference between the actual upper limit and actual lower of a given class interval. Therefore, the class size for the class interval 10-20 is 10.
The size of object of a class depends on the no. of bytes occupied by the data members of the class. }; The object of class student will occupy space of 8 bytes.
In C++, the Size of an empty structure/class is one byte as to call a function at least empty structure/class should have some size (minimum 1 byte is required ) i.e. one byte to make them distinguishable.
If you know the set of possible types, you can use RTTI to find out the dynamic type by doing dynamic_cast
. If you don't, the only way is through a virtual function.
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