Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determining size of a polymorphic C++ class

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?

like image 927
Tony the Pony Avatar asked Sep 11 '09 15:09

Tony the Pony


People also ask

How do you determine a class size?

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.

What is the size of an object of a class?

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.

What is the size of the object ABC of class ABC in B in C Plus Plus?

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.


1 Answers

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.

like image 137
sbi Avatar answered Sep 18 '22 22:09

sbi