Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
360 views
in Technique[技术] by (71.8m points)

c++ - find size of derived class object using base class pointer

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

struct base {
  virtual size_t size() const =0;
  virtual ~base() { }
};

template<typename T> 
struct intermediate : base {
  virtual size_t size() const { return sizeof(T); }
};

struct derived : intermediate<derived> 
{ };

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 derived will not get its own override of size]. There is a slightly more complex variant that gets around that.

struct base { /*as before */ };

template<typename Derived, typename Base>
struct intermediate : Base {
  virtual size_t size() const { return sizeof(Derived); }
};

struct derived : intermediate<derived, base>
{ };

struct further_derived : intermediate<further_derived, derived>
{ };

Basically, this inserts an intermediate in between each actual layer of your hierarchy, each overriding size with the appropriate behavior, and deriving from the actual base type. Repeat ad nauseum.

//what you want
base >> derived 
     >> more_deriveder
     >> most_derivedest

//what you get
base >> intermediate<derived, base> 
     >> derived >> intermediate<more_deriveder, derived> 
     >> more_deriveder >> intermediate<most_derivedest, more_deriveder> 
     >> most_derivedest

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...