Wednesday, January 22, 2025

Difference Between Reference And Pointers In C++

 This is a good video to refer to learn Difference Between Reference And Pointers In C++

Difference Between Reference And Pointers In C++


Pointer vs Reference (Interview Answer)

Pointer: A pointer is a variable that stores the memory address of another variable. It can be nullptr, can be reassigned to point to different objects, and supports pointer arithmetic.

Reference: A reference is an alias (another name) for an existing variable. It must be initialized when declared, cannot be nullptr in normal C++, and cannot be reseated to refer to another object. It behaves like the original variable.


Quick Comparison Table

PointerReference
Stores an addressAlias of an existing object
Can be nullptrCannot be nullptr (normal C++)
Can be reassignedCannot be reseated
Supports pointer arithmeticNo pointer arithmetic
Requires * to access valueUsed like a normal variable
Can point to dynamically allocated memoryTypically used for function parameters and return values

Example

int a = 10;
int b = 20;

int *p = &a;
int &r = a;

p = &b;   // OK: pointer now points to b

r = b;    // Does NOT make r refer to b
           // It copies b's value into a

Result:

a = 20
b = 20
r refers to a

Common Interview Questions & Answers

Q1: Can a pointer be nullptr?

Answer: Yes. A pointer can hold nullptr, indicating it does not point to any object.


Q2: Can a reference be nullptr?

Answer: No. A reference must always refer to a valid object in normal C++.


Q3: Can a pointer be reassigned?

Answer: Yes.

p = &b;

Q4: Can a reference be reassigned (reseated)?

Answer: No. Once initialized, a reference always refers to the same object.


Q5: When do you use a pointer?

Answer:

  • Dynamic memory (new/delete)
  • Optional objects (nullptr)
  • Polymorphism
  • Data structures (linked lists, trees)
  • Pointer arithmetic

Q6: When do you use a reference?

Answer:

  • Function parameters
  • Return values
  • Avoid copying large objects
  • Cleaner and safer syntax when an object is guaranteed to exist

30-Second Interview Answer

"A pointer is a variable that stores the address of another object. It can be null, reassigned, and supports pointer arithmetic. A reference is an alias for an existing object. It must be initialized, cannot be null in normal C++, and cannot be reseated. I use pointers when an object may be absent or for dynamic memory and polymorphism, while I use references for function parameters and return values when the object is guaranteed to exist."

Interview rating: If you can confidently give the 30-second answer and explain the r = b example correctly, you'd be answering this topic at the level expected of a senior C++ engineer.

lvalue vs rvalue

  1. What is an lvalue? An lvalue is an object that: Has an identifiable memory location. Has a name (in most cases). Can appear on th...