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;
}
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.
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".
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.
Last edited by Armen; November 19th, 2012 at 12:51 AM.
Reason: formatting
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.
Raju2001006
Please put [CODE][/CODE] tags around your code to preserve indentation and make it more readable...
Bookmarks