Reputation: 25
The output of the below code is 16. Why so? even without initializing with the length of array of the class the size is 16 and with initializing the length with the 2nd constructor, it is the same size i.e. 16. Any explanation?
#include <iostream>
#include <string>
using namespace std;
template <class T>
class array1{
T * arr;
int l;
public:
array1(){
arr = 0; l=0;
}
array1(int x){
l = x;
arr = new T[l];
}
~array1(){
delete[] arr;
}
void display(){
cout << "array1 is :"<<endl;
for (int i=0; i<l; i++)
cout << arr[i] << " ";
cout << endl;
}
};
int main()
{
array1<int> a1;
cout << "size of int arr is " << sizeof(a1);
return 0;
}
Upvotes: 0
Views: 1103
Reputation: 561
It is because of Data Structure alignment. In your system it is being aligned to 8 bytes word. Print the sizeof(T*)
and sizeof(int)
it will output 8
and 4
respectively in the constructor of array
class. But when output together it takes 16 bytes.
Upvotes: 2
Reputation: 1073
It appears your integer and pointer types are both 8 bytes/64 bits. Also, just a heads up, sizeof
is a compile-time operator, meaning that even if an object of your type allocates memory on the heap with the operator new[]
, sizeof
will still return 16 bytes for any object of type array1
.
Additionally, no matter what type you have for T
, sizeof(array1<T>)
will always be 16 bytes. (I am making the assumption that you are not compiling on an atypical target.)
Upvotes: 1
Reputation: 405
Your class has two member variables. A pointer and an int. I suspect that both are eight bytes in size for your platform.
If so, then: 8 + 8 = 16.
(Your class has no virtual methods -- so no vtable overhead).
Upvotes: 0