size of Polymorphic class
Hi,
I did know that the size of a class is increased by 4 bytes (32bit compiler) if the class has a virtual function.
I wrote one program and it is giving strange output.
I am using linux g++ compiler.
The program and output is as below
Code:
#include<iostream>
using namespace std;
class Base
{
public:
void fun()
{
}
private:
int i;
};
int main()
{
cout<<sizeof(Base)<<endl;
return 0;
}
output=4
Code:
#include<iostream>
using namespace std;
class Base
{
public:
virtual void fun()
{
}
private:
int i;
};
int main()
{
cout<<sizeof(Base)<<endl;
return 0;
}
output is 16
please clarify
Re: size of Polymorphic class
Quote:
Originally Posted by
Rajesh1978
Hi,
I did know that the size of a class is increased by 4 bytes (32bit compiler) if the class has a virtual function.
No. The sizeof() any object can increase by whatever amount the compiler sees fit. Nothing limits the increase to 4, 8, 16, or whatever number of bytes.
Quote:
I wrote one program and it is giving strange output.
I am using linux g++ compiler.
Nothing is "strange". That is what the sizeof() that object happens to be. The issue is that you cannot assume what the sizeof() any object is, as that is up to the compiler. If the output were 24, 28, 32 or any other value, that still isn't "strange".
Regards,
Paul McKenzie
Re: size of Polymorphic class
As it was mentioned it is up to compiler what the sizeof(Base) is. The only requirement is that the size of the class should be greater than zero. However if you want to understand from where 16 bytes for the second case might come from, you may look at data alignment (default or changed) for your structure/class.
Re: size of Polymorphic class
Yes, we can take data alignment as our source of issue here.
But, if we look at the points Rajesh1978 has mentioned here -
- it's a linux g++ compiler
- it's 32bit compiler
linux g++ compiler align data to it's exact bit values - means, it starts addressing the next variable, exactly from the next byte (hex-place).
So, in this case it could have taken 4+4=8 bytes long consecutive address space.
Please correct me if I am wrong here.
Re: size of Polymorphic class
What is the size of a pointer on your compiler ? i.e. sizeof(int*) ??
Re: size of Polymorphic class
BTW, if I recall correctly, gcc has a command line parameter to dump classes layouts ...
Re: size of Polymorphic class
Yes, you are right -
gcc/g++ -fdump-class-hierarchy source_file.cpp