PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, July 10, 2022

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

 July 10, 2022     c++, reference, sizeof     No comments   

Issue

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


Solution

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;
}


Answered By - Tom Clarke
Answer Checked By - Clifford M. (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing