sizeof empty class

D

deepakvsoni

what is the size of an class with not data members?
ex:
class A {
};

also
sizeof ?
class A{
int f(){
cout<<"Hello";
}
};
 
J

Jim Langston

what is the size of an class with not data members?
ex:
class A {
};

also
sizeof ?
class A{
int f(){
cout<<"Hello";
}
};

Usually 1. Why don't you try it?
 
D

deepakvsoni

Usually 1. Why don't you try it?

i've tried it... but why is it 1? Is it just for memory allocation so
that no two objects are allocated the same space?
 
J

Jim Langston

i've tried it... but why is it 1? Is it just for memory allocation so
that no two objects are allocated the same space?

Yes, among other considerations.
 
D

deepakvsoni

Yes, among other considerations.- Hide quoted text -

- Show quoted text -

so you mean to say the actual size of object is 0 but it is allocated
atleast 1 byte..
 
J

James Kanze

It's implementation defined. It's usually 1 on byte addressed
machines, but probably the same as sizeof(int) on a word
addressed machine.
i've tried it... but why is it 1? Is it just for memory allocation so
that no two objects are allocated the same space?

It's principally so that no two objects (of the same type) have
the same address. If you write something like:
A array[2] ;
you are guaranteed that &array[0] != &array[1].

Note that there are certain, very special cases where the
compiler is allowed to allocate less memory than the size of the
object. For example, given:

class A {} ;
class B : public A { int i ;} ;

With many compilers, sizeof( B ) == sizeof( int ), even though
sizeof( A ) + sizeof( int ) is larger. (This is called the
"empty base class" optimization.)
 
J

Jim Langston

so you mean to say the actual size of object is 0 but it is allocated
atleast 1 byte..

No, the size of the object is 1 byte. The compiler adds a padding byte.
Read James message, an array of 0 sized objects wouldn't work.
 

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,731
Messages
2,569,432
Members
44,832
Latest member
GlennSmall

Latest Threads

Top