msc
msc

Reputation: 34678

Why does the sizeof a class give different output in C++?

According to the cppreference,

When applied to a reference type, the result is the size of the referenced type.

But in the following program, compiler is giving different output.

#include <iostream>    
using namespace std;

class A 
{
    private:
        char ch;
        const char &ref = ch;
};

int main()
{
    cout<<sizeof(A)<<endl;
    return 0;
}

Output:

16

Here ch is of a character type and the reference is also of type character. So output would be 2 bytes instead of 16 bytes.

Online compiler: GDB

Upvotes: 0

Views: 133

Answers (1)

Tom Clarke
Tom Clarke

Reputation: 138

Firstly you're asking for the size of the object, not of the reference type itself.

sizeof(A::ref) will equal 1:

class A 
{
    public:
        char ch;
        const char &ref = ch;
};

int main()
{
    cout<<sizeof(A::ref)<<endl;
    return 0;
}

The object size is 16 because:

  1. The actual size taken up by the reference type inside the object is equal to the size of a pointer (8 in this case).
  2. Because the object alignment has increased to 8 due to the reference type, the char now also takes up 8 bytes even though it only really uses 1 byte of that space.

I.e. If you were to change char ch to char ch[8], sizeof(A) would still equal 16:

class A 
{
    private:
        char ch[8];
        const char &ref = ch[0];
};

int main()
{
    cout<<sizeof(A)<<endl;
    return 0;
}

Upvotes: 2

Related Questions