Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is sizeof Derived Class is 8?

Tags:

c++

#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

like image 462
vivek jain Avatar asked Nov 28 '13 16:11

vivek jain


People also ask

What is the size of derived class?

If compiled with the Microsoft C++ compiler, the size of DerivedClass is 16 bytes. If compiled with gcc (either c++ or g++), size of DerivedClass is 12 bytes.

What is the size of class in C++?

In C++, the Size of an empty structure/class is one byte as to call a function at least empty structure/class should have some size (minimum 1 byte is required ) i.e. one byte to make them distinguishable.

What is size of empty class in C++?

Size of Empty Class is = 1. Size of an empty class is not zero. It is 1 byte generally. It is nonzero to ensure that the two different objects will have different addresses. See the following example.

What is the size of an object of a class?

The size of object of a class depends on the no. of bytes occupied by the data members of the class. }; The object of class student will occupy space of 8 bytes.


2 Answers

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.

like image 66
Alok Save Avatar answered Oct 20 '22 15:10

Alok Save


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

like image 24
Rahul Tripathi Avatar answered Oct 20 '22 16:10

Rahul Tripathi