Akankshi Mishra
Akankshi Mishra

Reputation: 65

Reference memory allocation technique

I am confused with the size of reference
i have taken two example and compiled it

// Example program

#include <iostream>
#include <string>

using namespace std;

class ABC
{

    int &y;
    ABC(int a):y(a)
    {
    }
};
int main()
{
  std::cout <<sizeof(ABC)<<endl;  
  return 0;
}

o/p - 8

and when i am taking size of reference out side of class

// Example program

#include <iostream>
#include <string>

using namespace std;
int main()
{
    int y = 7;
    int &x = y;

    cout<<sizeof(x);
}

o/p - 4

please confirm why the size of reference differ in side of class or inside a function.

Upvotes: 2

Views: 44

Answers (1)

songyuanyao
songyuanyao

Reputation: 172924

why the size of reference differ in side of class or inside a function.

Because the object calculated by sizeof is different. For sizeof(x), sizeof operator will return the size of the referenced type, i.e. int.

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

And sizeof(ABC) will return the size of class ABC which contains a reference. They're not the same thing.

Note that for the case about class containing refrence, the standard does not say about how reference should be implemented and what should be the size for the representation, but in most implementation reference will be implemented as a pointer, and on 64-bit systems, addresses are 64 bits so you might get the result of 8.

Upvotes: 1

Related Questions