-2

I am new to C++ and was wondering whether references have memory in C++ .

#include <iostream>

int main()
{ 
    int a = 55;
    int& b = a;
    int* c = &b;
    int* d = &a;
    std::cout << (c)<<std::endl;
    std::cout << d;

}

This outputs: 0077F800 0077F800

If it points to the same address so is reference just another way of accessing the same variable?

  • 4
    It is not possible to get the address of a reference. The `&` operator gets the address of the referred object. It is also not possible to directly get the size of a reference. `sizeof` on a reference gets the size of the referred object. – François Andrieux Sep 22 '20 at 17:36
  • 3
    A reference is just another way of accessing a variable, but that doesn't tell you anything about whether they have memory or not. You're confusing the meaning of a reference (which is a C++ language question) with the implementation of references (which is a question about C++ compilers). – john Sep 22 '20 at 17:40
  • Thank You for answering the question, so in short, &b is just returning the address of the referred object and it doesn't have actual space in the memory? – Madhav Sharma Sep 23 '20 at 23:12

1 Answers1

-1
...
int a = 55;
int* c = &a;

std::cout << &a << std::endl;
std::cout << c  << std::endl;
... 

Both print statements shown here would yield the same memory address. However, there is a difference in their memory usage.

  1. std::cout << &a << std::endl; When we print &a, no memory is being allocated - which is also to say that this memory address is not being stored.

  2. In the other case, we are explicitly allocating a word of memory on the stack (4bytes on 32 bit systems). This memory is then being used to store the memory address of the variable a.

Do have a look the following question to understand the difference between allocation a pointer to a variable in stack vs in heap.