strange problem with OOP

O

openbysource

I wrote this program:

#include <iostream>
using namespace std;
class sample
{
private:
int age;
float salary;
char status;
};
int main()
{
sample s1;
cout << "sizeof int = " << sizeof(int) << endl;
cout << "sizeof float = " << sizeof(float) << endl;
cout << "sizeof char = " << sizeof(char) << endl;
cout << "sizeof sample class = " << sizeof(sample) << endl;
cout << "sizeof sample class object = " << sizeof(s1) << endl;
return 0;
}

Got this strange output:

sizeof int = 4
sizeof float = 4
sizeof char = 1
sizeof sample class = 12
sizeof sample class object = 12

Isn't it strange. I am using GCC 4.1.1. Isn't it should be 9 for the
last two one.
Please help.

Regards
 
A

Alf P. Steinbach

* openbysource:
I wrote this program:

#include <iostream>
using namespace std;
class sample
{
private:
int age;
float salary;
char status;
};
int main()
{
sample s1;
cout << "sizeof int = " << sizeof(int) << endl;
cout << "sizeof float = " << sizeof(float) << endl;
cout << "sizeof char = " << sizeof(char) << endl;
cout << "sizeof sample class = " << sizeof(sample) << endl;
cout << "sizeof sample class object = " << sizeof(s1) << endl;
return 0;
}

Got this strange output:

sizeof int = 4
sizeof float = 4
sizeof char = 1
sizeof sample class = 12
sizeof sample class object = 12

Isn't it strange. I am using GCC 4.1.1. Isn't it should be 9 for the
last two one.

The compiler pads the struct with three extra bytes to make it a
multiple of four bytes large.

Depending on the machine and OS, this might improve the speed of
accessing such structs in an array, or it may be necessary to access
them at all.

With most compilers you can configure this.
 

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,777
Messages
2,569,604
Members
45,234
Latest member
SkyeWeems

Latest Threads

Top