sizeof object

R

Radde

Hi all,

class A
{
};

int main()
{
A a;
cout<<"size "<<sizeof(a)<<endl;
}

Now if i run this, i get sizeof(a) = 1, size is 1byte. Experts say that
even class A is not having any members, 1 byte is to differentiate b/w
objects.

Suppose if i add one int data member to class A i.e

class A
{
int a;
};

int main()
{
A a;
cout<<"size "<<sizeof(a)<<endl;
}

I supposed to get size = 4 + 1 = 5.. but its 4.. Why is it?? Here how
does it differentiate between objects..

Whats the theory behind this??

Cheers..
 
V

Victor Bazarov

Radde said:
class A
{
};

int main()
{
A a;
cout<<"size "<<sizeof(a)<<endl;
}

Now if i run this, i get sizeof(a) = 1, size is 1byte. Experts say that
even class A is not having any members, 1 byte is to differentiate b/w
objects.

Yes, and that's one of the significant differences between C++ and C,
BTW.

The need to differentiate comes from the ability to create an array of
empty objects. If their size were 0, all of them would have the same
address, right? So, there would be no way to tell between them...
Suppose if i add one int data member to class A i.e

class A
{
int a;
};

int main()
{
A a;
cout<<"size "<<sizeof(a)<<endl;
}

I supposed to get size = 4 + 1 = 5.. but its 4.. Why is it?? Here how
does it differentiate between objects..

If the size is 4, couldn't you already differentiate? There is no need to
add another byte for that, is there?
Whats the theory behind this??

No theory. Just practice.

V
 

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,772
Messages
2,569,593
Members
45,108
Latest member
AlbertEste
Top