0

I happen to came across an case, where I have below class ( note that float is commented ) and when calculated the size. Output : 16. (can be verified on - http://th.cpp.sh/)

when float is added to this class, but to my surprise the size of class remain unchanged and still o/p : 16.

Shouldn't it output a value : 20 ?? (considering integer and vptr pointer are 8 bytes and float 4 bytes)

// Example program
#include <iostream>
#include <string>

class A
{
    public:
    int a;
//    float b;

    virtual void f();    
};


int main()
{
  std::cout << sizeof(A); 
  
  return 0;
}
  • 3
    *integer and vptr pointer are 8 bytes* - I've never seen `sizeof(int) == 8` on an actual system. Did you verify that it's indeed `8` with your compiler and hardware? (the particular online compiler you mention has `sizeof(int) == 4`: http://th.cpp.sh/6bzynv) – Yksisarvinen Sep 19 '22 at 12:00
  • 1
    there are no guarantees on the size of a class. In principle `sizeof(A)` could be 100, without breaking any rules set by the standard. – 463035818_is_not_an_ai Sep 19 '22 at 12:03
  • 3
    See [Why isn't sizeof for a struct equal to the sum of sizeof of each member?](https://stackoverflow.com/questions/119123/why-isnt-sizeof-for-a-struct-equal-to-the-sum-of-sizeof-of-each-member) Very likely. the size of the first (without the `float` member) is 16 bytes because of *padding* to make elements of `A` objects in an array nicely aligned. When the `float` member is added, it uses the before unused padding. – Some programmer dude Sep 19 '22 at 12:06
  • The `virtual void f();` functions adds 8 bytes to the size of the `class` (virtual function table or so). Remove the word `virtual` and you get the expected size of `4`. https://godbolt.org/z/3jEec1j8e – mch Sep 19 '22 at 12:17

0 Answers0