0

Why size of operator is showing 12 bytes instead of 9 for the below code in c++. As int occupies 4 bytes, float occupies 4 bytes and character occupies 1 byte, then sizeof should give 9 bytes as output instead of 12.

Object stores memory for data members only not member functions (methods).

#include <iostream>
using namespace std;

class Sample{

    public :
        int i;
        float a;
        char ch;

    public:

        Sample(int j, float b, char dh){
            i=j; a=b; ch=dh;
        }

};

int main(){

    Sample s1(10,3.14f, 'A');
    Sample s2(20,6.28f,'B');

    cout<<sizeof(s1)<<endl;
    cout<<sizeof(s2)<<endl;

    return 0;
}
  • Compilers are allowed to layout the internal structure of objects like they want and will typically align the members in a way that the CPU load/store can be done fast – Jakob Stark Feb 01 '22 at 10:55
  • 5
    @JakobStark not quite. The compiler is allowed to add padding but not reorder the fields (except in some cases that no compiler does afaik) – perivesta Feb 01 '22 at 11:10
  • 1
    The size of an object is the sum of the sizes of all the member variables, plus the size of all the intra-member padding for member alignment, plus the size of the inter-object padding for alignment, plus (if applicable) the size of the virtual function table pointer. – Eljay Feb 01 '22 at 12:58

0 Answers0