Is it possible to find the size of a derived class object using a base class pointer, when you don’t know the derived type.
Thank you.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
There’s no direct way, but you can write a virtual
size()method child classes can implement. An intermediary templates class can automate the leg work.This does require your hierarchy be polymorphic… however, requesting behavior based on the dynamic type of an object rather than its static type is part of the definition of polymorphic behavior. So this won’t add a v-table to the average use case, since at the very least you probably already have a virtual destructor.
This particular implementation does limit your inheritance tree to a single level without getting into multiple inheritance [ie, a type derived from
derivedwill not get its own override ofsize]. There is a slightly more complex variant that gets around that.Basically, this inserts an
intermediatein between each actual layer of your hierarchy, each overridingsizewith the appropriate behavior, and deriving from the actual base type. Repeat ad nauseum.Several mixin-type libraries make use of such a scheme, such that the mixins can be added to an existing hierarchy without introducing multiple inheritance. Personally, I rarely use more than a single level of inheritance, so I don’t bother with the added complexity, but your mileage may vary.