Virtual inheritance in C++, size of the grand child's object is heavy? -


this question has answer here:

i not explaining diamond problem in c++. know problem can solved using virtual inheritance. query had size of grandchild's object created heavier object created without virtual inheritance. let's consider below example better understanding

#include<iostream> using namespace std;  class base {  };  class child1 : virtual public base { };  class child2 : virtual public base {  };  class gchild : public child1, public child2 {  };  int main() {      gchild g;      cout<<sizeof(g)<<endl;      return 0; } 

sizeof g in above program 16 bytes, below program without virtual inheritance gives size 2 bytes

#include<iostream> using namespace std;  class base {  };  class child1 : public base { };  class child2 : public base {  };  class gchild : public child1, public child2 {  };  int main() {      gchild g;      cout<<sizeof(g)<<endl;      return 0; } 

can please explain me in detail why size varies huge difference?

the common way implement virtual function and virtual inheritance through virtual tables (or vtables). these added invisible member variables of classes, adding size.

the vtables stored separately means invisible member pointer table, , on 64-bit system pointer size typically 8 bytes (64 bits), , since have 2 virtual classes have 2 pointers leading 16 bytes of data.


as 2 bytes in second case, because object can't empty. able objects size, , more importantly able place object in memory, need take space, typically single byte enough. if create instance of base , gets instances size one.

why 2 bytes instead of one? have check compiler does, double-inheritance might have it.

since virtual classes have size through invisible vtable pointers, don't need "empty class" padding.


Comments

Popular posts from this blog

Command prompt result in label. Python 2.7 -

javascript - How do I use URL parameters to change link href on page? -

amazon web services - AWS Route53 Trying To Get Site To Resolve To www -