sizeof class

i am not able to understand the output for class derived2 and class derived4...can anyone please help me with the same
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#include <iostream>
using namespace std;
  
class Empty
{};
  
class Derived1 : public Empty
{};
  
class Derived2 : virtual public Empty
{};
  
class Derived3 : public Empty
{    
    char c;
};
  
class Derived4 : virtual public Empty
{
    char c;
};
  
class Dummy
{
    char c;
};
  
int main()
{
    cout << "sizeof(Empty) " << sizeof(Empty) << endl;
    cout << "sizeof(Derived1) " << sizeof(Derived1) << endl;
    cout << "sizeof(Derived2) " << sizeof(Derived2) << endl;
    cout << "sizeof(Derived3) " << sizeof(Derived3) << endl;
    cout << "sizeof(Derived4) " << sizeof(Derived4) << endl;    
    cout << "sizeof(Dummy) " << sizeof(Dummy) << endl;
 getchar(); 
    return 0;
}

As far as i know virtual is used to redefine a member of a class in its derived class....so why would it take memoryif nothing is defined in base class
Last edited on
Whenever a class is derived virtually, it adds a virtual pointer (vptr pointing to the vtable) to the class. Hence the size of Derived2 is equal to the size of pointer.

For Derived4, both vptr and padding come into picture.
To understand this better, try to add another int variable or int pointer to Dummy class, and check its size.
Since Derived4 is virtually derived, a pointer is added. Since a pointer variable and a char variable are present in the class, compiler will do padding and hence the size would be 8.

Further reading:
http://www.learncpp.com/cpp-tutorial/125-the-virtual-table/
http://www.cprogramming.com/tutorial/size_of_class_object.html
http://www.cplusplus.com/forum/general/17679/
Topic archived. No new replies allowed.