Question regarding size of the derived class

S

somenath

I am not able to understand the output of the following program?
#include<iostream>
using namespace std;

class Base{
protected:
int x;
char y;
};
class Derived:public Base {
protected:
char z;
};
int main(void)
{
cout<<"Sizeof (int) = "<<sizeof(int)<<endl;
cout<<"Sizeof (char) = "<<sizeof(char)<<endl;
cout<<"sizeof(Base) = "<<sizeof(Base)<<endl;
cout<<"sizeof(Derived) = "<<sizeof(Derived)<<endl;
return 0;
}

Output
+++++++++
Sizeof (int) = 4
Sizeof (char) = 1
sizeof(Base) = 8
sizeof(Derived) = 8

I can understand why sizeof(Base) = 8.

It is because sizeof(int) + sizeof(char) + padding = 4 + 1 + 3
But I expect sizeof(Derived) to be 12 because of sizeof(Base) + sizeof(Derived) + padding = 8 + 1 + 3 =12
But why the sizeof(Derived) is 8 ?
 
W

Wouter van Ooijen

somenath schreef op 23-Dec-13 4:44 AM:
class Base{
protected:
int x;
char y;
};
class Derived:public Base {
protected:
char z;
};
sizeof(Base) = 8
sizeof(Derived) = 8
But why the sizeof(Derived) is 8 ?

The 'real' size occupied by Base is 5 bytes, which is rounded up to 8 to
be 4-bytes aligned (or maybe even 8-byteds aligned) when a Base object
is allocated.

The size of the Base part of Derived is 5. The 'char z' does not require
more than 1-byte alignment, so the 'real' size of Derived is 6, which is
again rounded up to 8 when an object is aligned.

Wouter
 
I

Ian Collins

Paavo said:
First, memory layout is strictly implementation-defined, so another
compiler or the next version of the same compiler may give different
results.

You pipped me to the post!

By way of an example:

$ CC x.cc; ./a.out
Sizeof (int) = 4
Sizeof (char) = 1
sizeof(Base) = 8
sizeof(Derived) = 12

$ g++ x.cc; ./a.out
Sizeof (int) = 4
Sizeof (char) = 1
sizeof(Base) = 8
sizeof(Derived) = 8

Using POD structs:

$ g++ x.cc; ./a.out
Sizeof (int) = 4
Sizeof (char) = 1
sizeof(Base) = 8
sizeof(Derived) = 12
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,930
Messages
2,570,072
Members
46,522
Latest member
Mad-Ram

Latest Threads

Top