sizeof class ?

S

Sameer

Hi,
I have a class.
class C1
{
int i ;
char c ;
} ;

let me say the size of int is 4 and char is 1. Then if I say sizeof(C1)
it should be 5, why is it showing 8 ?
 
I

Ian Collins

Sameer said:
Hi,
I have a class.
class C1
{
int i ;
char c ;
} ;

let me say the size of int is 4 and char is 1. Then if I say sizeof(C1)
it should be 5, why is it showing 8 ?
Because your compiler aligns data on 4 byte boundaries, which is typical
on a 32 bit system.
 
S

Sameer

So how can I correct this? Is it only possible that the size of a class
is only multiple of size of int ?
 
J

Jim Langston

Sameer said:
So how can I correct this? Is it only possible that the size of a class
is only multiple of size of int ?

What do you mean by correcting it? It is correct. What is it about the
size that you don't like?

It may be possible to compact the class/structure by a compiler specific
switch, but this can cause problems. There are some systems that an
unaligned value can cause the CPU to not read it correctly. It can also
slow down operation.

I would suggest you just leave it alone and don't worry about the 3 extra
bytes.

If you really must compact it for some reason, look at your compilers
switches and such. If you're using a microsoft compiler look at #pragma
pack
 
S

Sameer

That question (How to make the size fo class exactly as the total size
of variables defined?) was asked with me in 2 interviews. Thats why i
asked.
 
M

Marcus Kwok

Rolf Magnus said:
Anything bigger than zero.

....as long as it is not an empty base class for a derived class. In
that case, it can be zero. However, on its own, I agree it must be
nonzero, so that distinct objects can be distinguished.


#include <iostream>

class Base { };

class Derived : public Base {
int x;
};

class OneInt {
int x;
};

int main()
{
std::cout << "sizeof int: " << sizeof(int) << '\n';
std::cout << "sizeof Base: " << sizeof Base << '\n';
std::cout << "sizeof Derived: " << sizeof Derived << '\n';
std::cout << "sizeof OneInt: " << sizeof OneInt << '\n';
}


/*
Output on my machine:
sizeof int: 4
sizeof Base: 1
sizeof Derived: 4
sizeof OneInt: 4
*/
 

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

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top