Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 504
null Avatar asked Feb 06 '13 08:02

null


1 Answers

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?

like image 68
PeddleSpam Avatar answered Oct 23 '22 11:10

PeddleSpam