in Programming
1,030 views
0 votes
0 votes
Assume that an integer and a pointer each takes 4 bytes. Also assume there is no alignment in objects. Predict the output
#include <iostream>
using namespace std;
class Test{
static int x;
int *ptr;
int y;
};
int main() {
// your code goes here
Test t;
int a;
cout<<sizeof(t)<<"\n";
cout<<sizeof(Test *);

return 0;
}
in Programming
by
1.0k views

2 Comments

edited by

I think it should be

12

4

because memory is allocated to the pointer and both integer variables in object t, so that's 4+4+4 = 12


And Test* is a pointer, so its size is 4 bytes

@N Thanks, that's right, only one copy of a static variable is created, and it's shared by all the objects of the class, that's why it's 8, not 12

0
0
edited by
Static members dont contribute to size. So it should be 4+4=8 and 4
1
1

1 Answer

3 votes
3 votes
Best answer

Since static members aren't allocated memory in class object as they are not considered part of the object. 

https://www.cprogramming.com/tutorial/size_of_class_object.html

So it will be 4+4=8 and 2nd will be 4

selected by
by