1
#include<iostream>

using namespace std;

class Node

{

    public:

        int data;

        Node *next;

};

int main()

{   

    Node* re=new Node();

    Node* t=new Node();

    re->data=2;

    re->next=t;

    cout<<sizeof(Node)<<endl;

    cout<<sizeof(re->data)<<endl;

    cout<<sizeof(re->next)<<endl;

}

Ouput:

16

4

8

How come the size of the class is coming out to be 16.

I get how the size of pointer is 8 bytes on a 64 bit machine and 4 bytes for integer. So shouldn't the size of the class be 12 (8 + 4) i.e. sum of the members of the class? Why there is an extra 4?

Patrick Roberts
  • 49,224
  • 10
  • 102
  • 153
anshul6297
  • 25
  • 4
  • It's called padding. Assuming a 64 bit operating system, the `next` member must be 8-byte aligned, so there's 4 bytes of padding between the `int` and the pointer in each instance. – Patrick Roberts Jun 03 '17 at 07:11

1 Answers1

1

The compiler adds extra space for alignment. So called memory padding. Here's a detailed explanation of it: padding and packaging

jboi
  • 11,324
  • 4
  • 36
  • 43