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
[expr.sizeof]
The
sizeof
a reference will return the size of the object referred to, in the case ofsizeof(ref)
this is equivalent tosizeof(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 thatsizeof(Test)
is 8.