C ++: virtual inheritance

Consider the code below:

#...
class A {};
class B: public A{};
class C: virtual public A{};
class D: virtual public C{};
// No More Classes
...
int _tmain(int argc, _TCHAR* argv[]) {
 cout<<sizeof(A)<<" ";
 cout<<sizeof(B)<<" ";
 cout<<sizeof(C)<<" ";
 cout<<sizeof(D)<<".";

 ...
}

O / P: 1 1 4 8.

Question:

  • sizeof (A) = 1 byte, and this place contains what is important for the compiler / us.
  • Why does the compiler want to add vptr to an object of class C when nothing exists.
  • If we do not have a virtual function, the compiler adds additional vptr to the derived objects.

*. its my 1st question here, please correct me if you find something is wrong.

+5
source share
2 answers

In short, this is not because the class is virtual or not, because the standard requires that all objects be distinguishable by their memory address. See this question:

Why is the size of an empty class in C ++ not equal to zero?

+8
source

ad 1. . PeddleSpam

ad 2. IIRC , VMT. , - A C.

ad 3. . 2.

0

All Articles