question about the memory allocation of class members

M

Metro12

Beyond my expectations, the result of the following program is 1
not 8. I want to know how the complier allocates memory for such a
class, and why the class Test's size does not contain the struct
TestNode's.

#include <iostream>
using namespace std;

class Test
{
public:
Test(){}
~Test() {}
private:
struct TestNode
{
int num;
char ch;
};
char ch1;
};

int main(void)
{
//the output is 1, not 8.Why?
cout << "size of Test: " << sizeof(Test) << endl;

return 0;
}

Thanks!
 
M

msalters

Metro12 schreef:
Beyond my expectations, the result of the following program is 1
not 8. I want to know how the complier allocates memory for such a
class, and why the class Test's size does not contain the struct
TestNode's.

Because you didn't declare a Test member with type TestNode (nor
nor... ). The compiler has no said:
#include <iostream>
using namespace std;

class Test
{
public:
Test(){}
~Test() {}
private:
struct TestNode
{
int num;
char ch;
};
TestNode node; // My guess, not the compiler's guess though.
char ch1;
};

HTH,
Michiel Salters
 
S

Srini

#include said:
using namespace std;

class Test
{
public:
Test(){}
~Test() {}
private:
struct TestNode
{
int num;
char ch;
};
char ch1;

};

int main(void)
{
//the output is 1, not 8.Why?
cout << "size of Test: " << sizeof(Test) << endl;

return 0;
}

struct TestNode is a nested struct. You have defined it but have not
*instantiated* it. So, there's no member object of type 'TestNode'
within the class 'Test'. The only member that Test has is the char
member whose size is what is the size of your class.

Srini
 
M

Metro12

Oh, I get it! It seems I've made another mistake---that when the struct
is instantiated, the size should be 12 not 8.
 
J

Jack Klein

Oh, I get it! It seems I've made another mistake---that when the struct
is instantiated, the size should be 12 not 8.

There is no 'should be', there is just 'is'. The implementation is
allowed wide latitude in using padding to align types on specific
boundaries. In some cases it is as simple as the fact that misaligned
values slow the program due to additional memory accesses. In other
cases, particularly with many RISC designs, the processor hardware
will generate a fault if memory accesses are misaligned.

Another compiler might well produce a different size. Even certain
options in the same compiler could do so as well.
 

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

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top