7
#include <iostream>
using namespace std;

class Empty
{};


class Derived : virtual public Empty
{
    char c;
};

int main()
{
    cout << "sizeof(Empty) " << sizeof(Empty) << endl;
    cout << "sizeof(Derived) " << sizeof(Derived) << endl;


    return 0;
}

Why size is coming 8 I think it should be 9, If I declare 'c' as integer then also its coming 8 Cany you please explain me the logic

vivek jain
  • 591
  • 4
  • 13
  • 28
  • 3
    Four bytes for the vtable, one byte for the char, three bytes of padding. Why do you think it should be nine? – john Nov 28 '13 at 16:14
  • You're probably on a 32-bit platform, so the vptr hidden inside your class will be 4 bytes. – Oliver Charlesworth Nov 28 '13 at 16:14
  • It's the first time I see `virtual` specified up in the inheritance list. Is this syntax legal? Is it better/safer than not specifying `virtual`? – Vittorio Romeo Nov 28 '13 at 19:31
  • 1
    @VittorioRomeo Yes it is legal. Whether it is better/safer than not specifying it depends on whether you need the virtual base class or not. (See: [What is a Virtual Base Class](http://stackoverflow.com/questions/21558/in-c-what-is-a-virtual-base-class)) – Andre Kostur Nov 28 '13 at 20:13

2 Answers2

10

The size is Implementation dependent and it depends on how the particular compiler implementation implements virtualism & padding. You shouldn't expect the value specifically to be something. If you want to calculate the size in your program just use sizeof and thats about it.

Alok Save
  • 202,538
  • 53
  • 430
  • 533
3

The size is dependent on implementation. Four bytes will be taken for the vtable, one byte is taken for the char, three bytes is for padding. That makes it 8 bytes. So it depends how your compiler is implementing the virtualism and padding. You can use sizeof if you want to calculate the size of your program

Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331
  • 1
    Not sure whether a vtable is needed here, or used. Virtual base class offsets can also be stored directly, and could also amount to 4 bytes. – MSalters Nov 28 '13 at 16:34
  • @MSalters:- Yes you are correct. But I think the first line of the answer is more important that it is dependent on implementation. Although I accept your point +1 – Rahul Tripathi Nov 28 '13 at 16:36
  • @OliCharlesworth:- SO will it be correct to say that **Four bytes** will be taken for the object which contains `vptr`? – Rahul Tripathi Nov 28 '13 at 16:55