Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Or you can use typeid, which might be faster than dynamic_cast (also with dynamic_cast you can cast to intermediary types in the hierarchy).</p> <p>It looks rather bad:</p> <pre><code>#include &lt;iostream&gt; #include &lt;typeinfo&gt; class Creature { char x[4]; public: virtual ~Creature() {} }; class Animal: public Creature { char x[8];}; class Bird: public Creature { char x[16]; }; class Dog: public Animal { char x[32]; }; class Cat: public Animal { char x[64]; }; class Parrot: public Bird { char x[128]; }; unsigned creature_size(const Creature&amp; cr) { if (typeid(cr) == typeid(Animal)) { return sizeof (Animal); } else if (typeid(cr) == typeid(Dog)) { return sizeof(Dog); } else if (typeid(cr) == typeid(Cat)) { return sizeof(Cat); } else if (typeid(cr) == typeid(Bird)) { return sizeof(Bird); } else if (typeid(cr) == typeid(Parrot)) { return sizeof(Parrot); } else if (typeid(cr) == typeid(Creature)){ return sizeof(Creature); } assert(false &amp;&amp; "creature_size not implemented for this type"); return 0; } int main() { std::cout &lt;&lt; creature_size(Creature()) &lt;&lt; '\n' &lt;&lt; creature_size(Animal()) &lt;&lt; '\n' &lt;&lt; creature_size(Bird()) &lt;&lt; '\n' &lt;&lt; creature_size(Dog()) &lt;&lt; '\n' &lt;&lt; creature_size(Cat()) &lt;&lt; '\n' &lt;&lt; creature_size(Parrot()) &lt;&lt; '\n' ; } </code></pre> <p>For each new type you'll need to add code to the creature_size function. With a virtual size function you'll need to implement this function in each class as well. However, this function will be significantly simpler (perfectly copy-n-pasteable, which shows there might be both a limitation in the language and a problem with your code design):</p> <pre><code>virtual unsigned size() const { return sizeof(*this); } </code></pre> <p>And you can make it abstract in the base class which means that it will be a compiler error if you forget to override this method.</p> <p>Edit: this is naturally assuming that given any Creature you want to know its size. If you have a strong reason to believe that you are dealing with a Dog - or a subclass of Dog (and you don't care if it is a subclass), then naturally you can use dynamic_cast for an <em>ad hoc</em> test.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload