null
null

Reputation: 807

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:

  1. sizeof(A) = 1byte, and this location hold what significant for compiler/us.
  2. Why compiler bother to add vptr in C class object when there is nothing actually resides.
  3. If we are not having any virtual function, compiler is adding an extra vptr to derived objects.

*. its' my 1st question here, please correct me if you found anything wrong.

Upvotes: 5

Views: 230

Answers (2)

wilx
wilx

Reputation: 18268

ad 1. See PeddleSpam's answer

ad 2. IIRC the compiler puts more information than just virtual functions pointers into the so called VMT. One more information is the position of the virtual A in C, I think.

ad 3. See 2.

Upvotes: 0

PeddleSpam
PeddleSpam

Reputation: 438

In short it's not due to the class being virtual or not, it's 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 zero?

Upvotes: 8

Related Questions