开发者

How to eliminate a copy of variable in base class with multiple inheritance?

As title describes, I have 3 classes:

#include <iostream>

using namespace std;

class first
{
protected :
 int data;
public :
 first() 
  :data( 1 )
 {
  // empty 
 }

};

class second : public first 
{
protected :
 double x;
public :
 second() 
  :first() 
 {
  // empty
 }
};

class combine : public first, public second
{
public :
 combine()
 {
  // empty
 }

};

int main()
{
 combine c;
 cout << sizeof(开发者_运维问答 c ) << endl;

 return 0;
}

When I check the sizeof( first ) is 4 which make sense to me. But I don't know why sizeof( second ) is 16 ( I assumed 4 + 8 = 12 != 16 ), and sizeof( combine ) is 24 ( 4 + 4 + 8 = 16 != 24 ). Could anyone help me to explain this? Further, when 'combine' multiple inherits from 'first' and 'second', I realized that its size includes both data ( int ) from 'first' and 'second' class; which is a waste of memory. Is there any way to work around this issue, i.e. let 'first' and 'second' share one copy of 'data'?


This is what virtual inheritance is for. To keep first from being duplicated, everywhere you (directly) derive a class from first, you need to make the inheritance virtual, so you'd have:

class second : public virtual first { // ...

class combine : public virtual first, public second { // ...


Looks like the alignment is set to 8. This means that every sizeof above 8 is rounded up to a multiple of 8. Sizes below 8 are rounded to 8, 4, 2, or 1.

E.g.

  • First: int = 4.
  • Second: int + double = 4 + 8 = 12, round up to 16
  • Combine: int + second = 4 + 16 = 20, round up to 24.

And yes, the first::data is duplicated in combine. Use virtual inheritance (see other answers) to solve that. Or adjust your inheritance relations.

This is done in order to enhance memory access times at the cost of additional memory used.

If you can't spare the additional memory, look up the compiler magic to set the alignment to a lower value. Luckily, this is rarely needed.


If you really need this construction, you can use virtual inheritance:

http://www.parashift.com/c++-faq-lite/multiple-inheritance.html#faq-25.9

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜