Victor Bazarov wrote:
Radde wrote: #include<iostream.h>
#include <iostream>
class A
{
//char i;
};
class B
{
//char i;
};
class C: public A, public B
{
private:
int i;
};
void main()
int main()
{
C c;
cout<<"size is "<<sizeof(c)<<endl;
std::cout<<"size is "<<sizeof(c)<<std::endl;
}
When i run above code, iam getting size as 8, actually there is only
one int variable, it should be 4, why is it 8??
Probably because your default compiler options make alignment at 8-byte
boundary. No way to tell. Alignment and padding are compiler-specific.
The question being asked is why an instance of class C is larger than
an instance of class A or class B, not why it is four bytes larger. The
question is a good one. There would seem to be no apparent reason why a
compiler would increase the size of C when it inherits from A and B,
even when the amount of data that class C stores remains unchanged. And
in fact the only reason that the C++ compiler makes C larger in this
situation is because the C++ Standard requires it.
The C++ Standard says that neither class A or class B in this situation
can be of size zero bytes. Therefore an object of class C will
necessarily have to be larger than either of its two base classes,
because C's size cannot be zero bytes either. The answer has nothing to
do with padding or alignment, but rather conformity with the Standards.
Granted, the Standard doesn't say how much larger C has to be, but it
does explain why C is larger than A or B. And that really is the
question being asked.
Note that the "empty base class optimization" would make classes A and
B add zero incremental bytes to objects of type C. To take advantage of
this optimization (if the compiler supports it) classes A and B must
each derive from an empty base class themselves.
Suppose if i move int variable from class C to clas A, then size is 4.
why is it 8 if we add variable to class C?
You need to ask in the newsgroup dedicated to your compiler. Those issues
are compiler-specific and are not defined in the language Standard.
The Standard does tell us that moving the declaration from a derived to
base class around will not change the relative sizes of the classes
involved. And knowing that fact is sufficient to answer this question.
Greg