Reference as a only class member gives size 8 for integer

144 views Asked by At

I came across this scenario while writing a small c++ program to test reference as a class member.

Having reference only as a class member, the program is giving a o/p of 8. Generally reference gives the size as the particular data type they are of. But why it is 8 here(instead of 4). Please help me in understanding it.

#include<iostream>
using namespace std;

class Test {
    int &t;
public:
    Test(int &t):t(t) {}
};

int main()
{
    int x = 20;
    Test t1(x);
    int &ref = x;
    cout<<sizeof(ref)<<endl;
    cout<<sizeof(t1)<<endl;
    return 0;
}

Output -

/home/user>./a.out
4
8
1

There are 1 answers

0
user657267 On BEST ANSWER

[expr.sizeof]

2 When applied to a reference or a reference type, the result is the size of the referenced type. When applied to a class, the result is the number of bytes in an object of that class including any padding required for placing objects of that type in an array.

The sizeof a reference will return the size of the object referred to, in the case of sizeof(ref) this is equivalent to sizeof(int), which on your platform is 4.

Your class on the other hand needs to store a reference to an int, the standard doesn't specify how implementations should achieve this but they are commonly, if not universally, stored as pointers behind the scenes. sizeof(int*) on your platform is presumably 8, but the details are not important, all you need to know is that sizeof(Test) is 8.