5

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.

TemplateRex
  • 69,038
  • 19
  • 164
  • 304
null
  • 777
  • 1
  • 7
  • 12
  • For a first question here: +1 for a good, well formatted and self-explanatory post. – Kiril Kirov Feb 06 '13 at 08:08
  • 2
    I don't really see any questions, just a list of statements. – Some programmer dude Feb 06 '13 at 08:08
  • @JoachimPileborg - "2. Why compiler bother to add vptr in C class object when there is nothing actually resides". I guess `3.` is the same as `.2`. And `1.` is most likely - showing that the OP knows why the result is `1`. – Kiril Kirov Feb 06 '13 at 08:10
  • excellent and interesting first question – Elemental Feb 06 '13 at 08:13
  • 1
    @meh A question usually ends with a question mark (like this one `?`). The code is not full (ie doesn't compile), and with window's extensions. Therefore, I wouldn't call it a well formatted and self-explanatory post. – BЈовић Feb 06 '13 at 08:25
  • @BЈовић - I also wrote "for a first question here". Most of the "first" questions here are much, much worse than this one, aren't they? – Kiril Kirov Feb 06 '13 at 08:26

2 Answers2

8

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?

Community
  • 1
  • 1
PeddleSpam
  • 418
  • 3
  • 10
0

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.

Community
  • 1
  • 1
wilx
  • 17,697
  • 6
  • 59
  • 114