Suchin Raj Suchin Raj - 1 month ago 6
C++ Question

Size of class object in C++

On what basis is size of class object shown as 12?

class testvector
{
public : vector<int> test;
};
int main()
{
testvector otestvector;
cout<<"size :"<<sizeof(otestvector)<<"\n";
cout<<"size of int :"<<sizeof(int);
}


Output:

size :12
size of int :4

Answer

Think of it like this. Let's imagine the standard C++ library didn't have a vector class. And you decided it would be a good idea to have one.

You just might, at a very minimum, come up with something like this. (Disclaimer: the actual vector class for C++ is far more complicated)

template <class T>
class vector
{
    T* items;        // array of items
    size_t length;   // number of items inserted
    size_t capacity; // how many items we've allocated


   public:
     void push_back(const T& item) {
         if (length >= capacity) {
             grow(length * 2); // double capacity
         } 
        items[length] = item;
        length++;
     }

    ...
};

Let's break down an instance of my simple vector class down on a 32-bit system:

 sizeof(items) == 4   // pointers are 4 bytes on 32-bit systems
 sizeof(length) == 4; // since size_t is typically a long, it's 32-bits as well
 sizeof(capacity) == 4; // same as above

So there's 12 bytes of member variables just to start out. Hence sizeof(vector<T>) == 12 for my simple example. And it doesn't matter what type T actually is. The sizeof() operator just accounts for the member variables, not any heap allocations associated with each.

The above is just a crude example. The actual vector class has a more complex structure, support for custom allocators, and other optimizations for efficient iterations, insertion, and removal. Hence, likely more member variables inside the class.

So at the very least, my minimum example is already 12 bytes long. Probably will be 24 bytes on a 64-bit compiler since sizeof(pointer) and sizeof(size_t) typically double on 64-bit.

Comments